package com.huadao.cart_ccs.experiment.home;

import android.util.Log;
import android.view.View;

import com.huadao.cart_ccs.Event.LiquidLoopPlanEvent;
import com.huadao.cart_ccs.common.ExperimentStageManager;
import com.huadao.cart_ccs.common.ParamsPreferences;
import com.huadao.cart_ccs.common.ProjectManager;
import com.huadao.cart_ccs.common.RockToast;
import com.huadao.cart_ccs.common.UtilHelpers;
import com.huadao.cart_ccs.common.deviceController.BasePumpController;
import com.huadao.cart_ccs.common.deviceController.CO2Controller;
import com.huadao.cart_ccs.common.deviceController.CirculatingPumpController;
import com.huadao.cart_ccs.common.deviceController.CultureTankController;
import com.huadao.cart_ccs.common.deviceController.FluidIntakePumpController;
import com.huadao.cart_ccs.common.deviceController.MagneticStirrerController;
import com.huadao.cart_ccs.common.deviceController.MediumValveController;
import com.huadao.cart_ccs.common.deviceController.O2Controller;
import com.huadao.cart_ccs.common.deviceController.ReclaimPumpController;
import com.huadao.cart_ccs.common.deviceController.SalineValveController;
import com.huadao.cart_ccs.common.deviceController.TemperatureController;
import com.huadao.cart_ccs.common.deviceController.WastePumpController;
import com.huadao.cart_ccs.common.scheudle.ScheduleUtil;
import com.huadao.cart_ccs.data.bean.EnvironmentLog;
import com.huadao.cart_ccs.data.bo.BaseBO;
import com.huadao.cart_ccs.data.bo.CO2BO;
import com.huadao.cart_ccs.data.bo.ChangeLiquidAmount;
import com.huadao.cart_ccs.data.bo.CommandWord;
import com.huadao.cart_ccs.data.bo.CultureTankBO;
import com.huadao.cart_ccs.data.bo.DeviceBO;
import com.huadao.cart_ccs.data.bo.DoorBO;
import com.huadao.cart_ccs.data.bo.ElectronicScaleBO;
import com.huadao.cart_ccs.data.bo.IncubatorBO;
import com.huadao.cart_ccs.data.bo.LiquidLevelBO;
import com.huadao.cart_ccs.data.bo.MagneticStirrerBO;
import com.huadao.cart_ccs.data.bo.O2BO;
import com.huadao.cart_ccs.data.bo.OperationLogBO;
import com.huadao.cart_ccs.data.bo.PeristalticPumpBO;
import com.huadao.cart_ccs.data.bo.TemperatureBO;
import com.huadao.cart_ccs.data.bo.UltravioletLightBO;
import com.huadao.cart_ccs.data.bo.ValveBO;
import com.huadao.cart_ccs.data.source.http.RockBaseObserver;
import com.huadao.cart_ccs.data.task.ChangeLiquidBO;
import com.huadao.cart_ccs.data.task.ChangeLiquidTask;
import com.huadao.cart_ccs.data.task.CleanPipesTask;
import com.huadao.cart_ccs.data.task.CultureTankTask;
import com.huadao.cart_ccs.data.task.IncubatorTask;
import com.huadao.cart_ccs.data.task.LiquidLoopTask;
import com.huadao.cart_ccs.data.task.OperateTask;
import com.huadao.cart_ccs.data.task.ShakeTableTask;
import com.huadao.cart_ccs.data.task.StirrerTask;
import com.huadao.cart_ccs.data.task.UltravioletLightTask;
import com.huadao.cart_ccs.exception.ExceptionCode;
import com.huadao.cart_ccs.exception.ExceptionType;
import com.huadao.cart_ccs.experiment.paramsSetting.ParamConsts;
import com.huadao.cart_ccs.greendao.GreenDaoManager;
import com.huadao.cart_ccs.greendao.entity.DeviceRecord;
import com.huadao.cart_ccs.greendao.entity.ExceptionInfo;
import com.huadao.cart_ccs.greendao.entity.Injection;
import com.huadao.cart_ccs.greendao.entity.LiquidLoopPlan;
import com.huadao.cart_ccs.greendao.entity.Operation;
import com.huadao.cart_ccs.greendao.entity.Sample;
import com.huadao.cart_ccs.greendao.gen.LiquidLoopPlanDao;
import com.huadao.cart_ccs.main.CartApplication;
import com.huadao.cart_ccs.main.CommandService;
import com.huadao.cart_ccs.modle.CO2Modle;
import com.huadao.cart_ccs.modle.CultureTankModle;
import com.huadao.cart_ccs.modle.DeviceModle;
import com.huadao.cart_ccs.modle.DeviceRuntimeLogModle;
import com.huadao.cart_ccs.modle.DoorModle;
import com.huadao.cart_ccs.modle.ElectronicScaleModle;
import com.huadao.cart_ccs.modle.IncubatorModle;
import com.huadao.cart_ccs.modle.LiquidLevelModel;
import com.huadao.cart_ccs.modle.MagneticStirrerModel;
import com.huadao.cart_ccs.modle.O2Modle;
import com.huadao.cart_ccs.modle.OperationLogModel;
import com.huadao.cart_ccs.modle.PeristalticPumpModle;
import com.huadao.cart_ccs.modle.ProjectModle;
import com.huadao.cart_ccs.modle.PumpControlModle;
import com.huadao.cart_ccs.modle.TemperatureModle;
import com.huadao.cart_ccs.modle.UltravioletLightModle;
import com.huadao.cart_ccs.modle.ValveModle;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.greenrobot.greendao.async.AsyncSession;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class ExperimentPresenter extends ExperimentContract.IExperimentPresenter implements CommandService.CommandCallBack {
    private CultureTankModle cultureTankModle;
    private PeristalticPumpModle peristalticPumpModle;
    private MagneticStirrerModel magneticStirrerModel;
    private CO2Modle co2Modle;
    private O2Modle o2Modle;
    private TemperatureModle temperatureModle;
    private UltravioletLightModle ultravioletLightModle;
    private LiquidLevelModel liquidLevelModel;
    private ElectronicScaleModle electronicScaleModle;
    private IncubatorModle incubatorModle;
    private DoorModle doorModle;
    private ValveModle valveModle;
    private ProjectModle projectModle;
    private DeviceRuntimeLogModle deviceRuntimeLogModle;
    private OperationLogModel operationLogModel;

    private ScheduledFuture scheduledCO2;
    private ScheduledFuture scheduledO2;
    private ScheduledFuture scheduledTemperature;
    private ScheduledFuture scheduledLiquidLevel;
    private ScheduledFuture scheduledFutureExperiment;
    private ScheduledFuture scheduledFuturePumpFluidIntake;
    private ScheduledFuture scheduledFuturePumpWaste;
    private ScheduledFuture scheduledFuturePumpCircling;
    private ScheduledFuture scheduledFuturePumpReclaim;
    private ScheduledFuture scheduledChangeAir;
    private Date lastTimeChangeAir;
    private ScheduledFuture scheduledWeight;
    //    private ScheduledFuture scheduledFutureRequestEnvironmentLog;
    private Disposable disposable_RequestEnvironment;

    private LiquidLoopTask inputLiquidTask;
    private LiquidLoopTask circleTask;
    private LiquidLoopTask wasteTask;
    private LiquidLoopTask reclaimTask;
    private ChangeLiquidTask changeLiquidTask;
    private CleanPipesTask cleanPipesTask;
    private StirrerTask stirrerTask;
    private CultureTankTask cultureTankTask;
    private IncubatorTask incubatorTask;
    private UltravioletLightTask ultravioletLightTask;
    private ShakeTableTask shakeTableTask;

    private boolean isStartingCulture = false;
    private boolean isPauseingCulture = false;
    private boolean isResumingCulture = false;

    private boolean isFluidIntaking;
    private boolean isFluidOutTaking;
    private boolean isCollecting;
    //    private boolean isChangeLiquid;
    private boolean isStartNewProject;
    //是否在初始化培养液
    private boolean isInitCultureLiquid;
    //是否在冲刷
    private boolean isSour;
    //是否在清洗管路
    private boolean isCleanPipes;

    private double currentCO2;
    private double currentO2;
    private double currentTemperature;

    //连续接收到的液位异常次数，达到3次就报警
    private int levelLiquid_warning;

    private AsyncSession asyncSession;

    private Disposable fluidIntakDisposable;
    private Disposable fluidOutDisposable;
    private Disposable collectDisposable;

    private LiquidLoopPlanDao liquidLoopPlanDao;

    private Map<LiquidLoopPlan,ScheduledFuture> planScheduledFutureMap;

    private boolean isTesting;

    private int maxCount = 3;
    private int closeFluidIntakenFailedCount;
    private int closeWastFailedCount;
    private int closeCirclingFailedCount;
    private int closeReclaimFailedCount;
    private int circlingChangeDirectionWithoutExpected;//循环泵改变转向读到的次数

    //读称重失败次数
    private int readWeightFailedTimes;

    //项目是否开启，开启项目需要调接口
    private boolean isProjectStarted;

    public ExperimentPresenter(ExperimentContract.IExperimentView baseView) {
        attachView(baseView);
        magneticStirrerModel = new MagneticStirrerModel();
        peristalticPumpModle = new PeristalticPumpModle();
        cultureTankModle = new CultureTankModle();
        incubatorModle = new IncubatorModle();
        co2Modle = new CO2Modle();
        o2Modle = new O2Modle();
        temperatureModle = new TemperatureModle();
        ultravioletLightModle = new UltravioletLightModle();
        liquidLevelModel = new LiquidLevelModel();
        electronicScaleModle = new ElectronicScaleModle();
        doorModle = new DoorModle();
        valveModle = new ValveModle();
        projectModle = new ProjectModle(baseView.getContext());
        deviceRuntimeLogModle = new DeviceRuntimeLogModle(baseView.getContext());
        operationLogModel = new OperationLogModel(baseView.getContext());
        EventBus.getDefault().register(this);

        asyncSession = GreenDaoManager.getInstance().getAsyncNoCacheSession();
        liquidLoopPlanDao = GreenDaoManager.getInstance().getSession().getLiquidLoopPlanDao();
        planScheduledFutureMap = new HashMap<>();
    }

    //仅用于测试
    @Override
    public void setIsTesting(boolean isTesting) {
        this.isTesting = isTesting;
    }

    @Override
    void moveToCorrectStage() {
        //        if (ExperimentStageManager.getInstance().getCurrentStage().getDay() == 0) {
        //            ExperimentStageManager.getInstance().forwardStage();
        //        }
        baseView.moveToStage(ExperimentStageManager.getInstance().getCurrentStage());
    }

    @Override
    public void setEnvironment() {
        setTemperature(ParamsPreferences.getInstance().getTemperature());
        setCO2(ParamsPreferences.getInstance().getCO2());
        setO2(ParamsPreferences.getInstance().getO2());
    }

    @Override
    public void recoverAD() {
        byte[] ad = ParamsPreferences.getInstance().getAD();
        peel(ad);
    }

    @Override
    public void requestOperationLog(String behavior, String note) {
        Observable<OperationLogBO> observable = operationLogModel.createOperation(behavior, note);
        operationLogModel.toSubscribe(observable, new RockBaseObserver<OperationLogBO>() {
            @Override
            protected void onBaseNext(OperationLogBO data) {

            }
        });
    }

    //停止所有任务
    @Override
    public void stopAllTask() {
        if (changeLiquidTask != null) {
            changeLiquidTask = null;
        }
        if (cleanPipesTask != null) {
            cleanPipesTask = null;
            isCleanPipes = false;
        }
        if (inputLiquidTask != null) {
            if (inputLiquidTask.isRunned()) {
                closePumpTask(PeristalticPumpBO.PeristalticPump_fluidIntake, null);
            }
        }
        if (wasteTask != null) {
            if (wasteTask.isRunned()) {
                closePumpTask(PeristalticPumpBO.PeristalticPump_waste, null);
            }
        }
        if (reclaimTask != null) {
            if (reclaimTask.isRunned()) {
                closePumpTask(PeristalticPumpBO.PeristalticPump_reclaim, null);
            }
        }
        if (stirrerTask != null) {
            if (stirrerTask.isRunned()) {
                closeStirrerTask(null);
            }
        }
        if (cultureTankTask != null) {
            if (cultureTankTask.isRunned()) {
                closeCultureTankTask(null);
            }
        }
        if (incubatorTask != null) {

        }
        if (ultravioletLightTask != null) {

        }
        if (shakeTableTask != null) {
            if (shakeTableTask.isRunned()) {
                closeShakeTableTask();
            }
        }
    }

    @Override
    public String checkBeforeSample() {
        //判断是否已经在取样
        return null;
    }

    @Override
    public String checkBeforeInject() {
        //判断是否已经在进样
        return null;
    }

    @Override
    public String checkBeforeCleanPipes() {
        //判断是否已经有管路清洗任务
        //判断是否已经有进液任务
        //判断是否已经有排液任务
        //判断是否已经有换液任务
        //判断是否已经在进样
        return null;
    }

    @Override
    public CleanPipesTask getCleanPipeTask() {
        return cleanPipesTask;
    }

    @Override
    public LiquidLoopTask getFluidIntakenTask() {
        return inputLiquidTask;
    }

    @Override
    public LiquidLoopTask getDischargeTask() {
        return wasteTask;
    }

    @Override
    public LiquidLoopTask getCollectTask() {
        return reclaimTask;
    }

    @Override
    public ChangeLiquidTask getChangeLiquidTask() {
        return changeLiquidTask;
    }

    //清洗管路
    @Override
    public void cleanPipes(String taskName, int fluidAmount, int wasteAmount, int cleanNumbers, int loopTime, int fluidSpeed, int circlingSpeed, int wasteSpeed) {
        clearCleanPipeTask();

        Operation operation = new Operation();
        operation.setOperator(CartApplication.getInstance().getOperator());
        operation.setDateTime(new Date());
        operation.setData(Operation.Operate_CleanPipes);
        saveOperation(operation);


        cleanPipesTask = new CleanPipesTask(fluidAmount, wasteAmount, cleanNumbers, loopTime * 60, fluidSpeed, circlingSpeed, wasteSpeed);
        isCleanPipes = true;
        cleanPipesTask.setState(OperateTask.STATE_STARTING);
        fluidIntake(fluidAmount, fluidSpeed, LiquidLoopTask.Liquid_saline, "系统", new Date(), null);
        cleanPipesTask.setInputLiquidTask(inputLiquidTask);
        cleanPipesTask.setTaskName(taskName);
    }

    @Override
    public void terminateCleanPipe() {
        cleanPipesTask.setTerminate(true);
        terminateFluidIntake();
        terminateCircle();
        terminateDischarge();
    }

    private void clearCleanPipeTask() {
        if (cleanPipesTask != null) {
            if (cleanPipesTask.getInputLiquidTask() != null) {
                cleanPipesTask.getInputLiquidTask().cancelCloseTask();
            }
            if (cleanPipesTask.getWasteTask() != null) {
                cleanPipesTask.getWasteTask().cancelCloseTask();
            }
            if (cleanPipesTask.getCirclingTask() != null) {
                cleanPipesTask.getCirclingTask().cancelCloseTask();
            }
            cleanPipesTask = null;
        }
        isCleanPipes = false;
    }

    @Override
    public void initCultureLiquid(int amount) {
        isInitCultureLiquid = true;
        baseView.showToast("开始注入初始培养液 " + amount + " ml");

        Operation operation = new Operation();
        operation.setDateTime(new Date());
        operation.setName(Operation.Operate_FluidIntake);
        operation.setData(ParamConsts.initCultureLiquid + "ml");
        operation.setOperator("系统");

        fluidIntake(amount, ParamsPreferences.getInstance()
                                             .getFluidIntakePumpSpeed(), LiquidLoopTask.Liquid_medium, "系统", new Date(), operation);
    }

    @Override
    void scheduleReadCO2() {
        if (scheduledCO2 != null && !scheduledCO2.isCancelled()) {
            return;
        }
        scheduledCO2 = ScheduleUtil.getInstance().scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                co2Modle.readCO2();
                //debug
                //                electronicScaleModle.weight();
                if (CO2Controller.getInstance().isCurrentValueExpired()) {
                    baseView.runOnUi(new Runnable() {
                        @Override
                        public void run() {
                            baseView.readCO2Failed();
                        }
                    });
                }
            }
        }, 0, ParamConsts.CO2ReadFrequency, TimeUnit.SECONDS);
    }

    @Override
    void scheduleReadO2() {
        if (scheduledO2 != null && !scheduledO2.isCancelled()) {
            return;
        }
        scheduledO2 = ScheduleUtil.getInstance().scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                o2Modle.readO2();
                if (O2Controller.getInstance().isCurrentValueExpired()) {
                    baseView.runOnUi(new Runnable() {
                        @Override
                        public void run() {
                            baseView.readO2Failed();
                        }
                    });
                }
            }
        }, 0, ParamConsts.O2ReadFrequency, TimeUnit.SECONDS);
    }

    @Override
    void scheduleReadTemperature() {
        if (scheduledTemperature != null && !scheduledTemperature.isCancelled()) {
            return;
        }
        scheduledTemperature = ScheduleUtil.getInstance().scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                temperatureModle.readTemperature();
                if (TemperatureController.getInstance().isCurrentValueExpired()) {
                    baseView.runOnUi(new Runnable() {
                        @Override
                        public void run() {
                            baseView.readTemperatureFailed();
                        }
                    });
                }
            }
        }, 0, ParamConsts.temperatureReadFrequency, TimeUnit.SECONDS);
    }

    //delay 秒
    @Override
    public void scheduleChangeAir(int delay) {
        if (scheduledChangeAir != null && CultureTankController.getInstance().getSpeed() > 0) {
            closeCultureTankTask(null);
        }
        scheduledChangeAir = ScheduleUtil.getInstance().scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                int time = UtilHelpers.calculateTimeByAirAmount(ParamsPreferences.getInstance().getChangeAirAmount());
                changeAir(time);
            }
        }, delay, ParamsPreferences.getInstance().getChangeAirFrequency(), TimeUnit.SECONDS);
    }

    @Override
    public void scheduleWeight() {
        if (scheduledWeight != null && !scheduledWeight.isCancelled()) {
            return;
        }
        scheduledWeight = ScheduleUtil.getInstance().scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                electronicScaleModle.weight();
            }
        }, 0, ParamConsts.WeightReadFrequency, TimeUnit.SECONDS);
    }

    @Override
    public void stopScheduleWeight() {
        if (scheduledWeight != null) {
            scheduledWeight.cancel(true);
            scheduledWeight = null;
        }
    }

    @Override
    public void cancelScheduleChangeAir() {
        if (scheduledChangeAir != null) {
            scheduledChangeAir.cancel(true);
            scheduledChangeAir = null;
            cultureTankTask.cancelCloseTask();
        }
    }

    @Override
    public void scheduleRequestEnvironmentParams() {
        disposable_RequestEnvironment = Observable.interval(10, ParamConsts.sendEnvironmentFrenquency, TimeUnit.SECONDS)
                                                  .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                                                  .subscribe(new Consumer<Long>() {
                                                      @Override
                                                      public void accept(Long aLong) throws Exception {
                                                          Double CO2 = null;
                                                          Double O2 = null;
                                                          Double Temperature = null;
                                                          if (!CO2Controller.getInstance().isCurrentValueExpired()) {
                                                              CO2 = CO2Controller.getInstance().getCurrentValue();
                                                          }
                                                          if (!O2Controller.getInstance().isCurrentValueExpired()) {
                                                              O2 = O2Controller.getInstance().getCurrentValue();
                                                          }
                                                          if (!TemperatureController.getInstance().isCurrentValueExpired()) {
                                                              Temperature = TemperatureController.getInstance()
                                                                                                 .getCurrentValue();
                                                          }
                                                          //如果长时间未收到下位机返回则判定异常，或者任意一项数值超出误差范围也判断为异常
                                                          int state;
                                                          if (CO2 == null || O2 == null || Temperature == null || !CO2Controller
                                                                  .getInstance().isInControl() || !O2Controller.getInstance()
                                                                                                               .isInControl() || !TemperatureController
                                                                  .getInstance().isInControl()) {
                                                              state = EnvironmentLog.ABNORMAL;
                                                          } else {
                                                              state = EnvironmentLog.NORMAL;
                                                          }
                                                          requestEnvironment(CO2, O2, Temperature, state);
                                                      }
                                                  });
    }

    public void requestEnvironment(Double CO2, Double O2, Double Temperature, int state) {
        Observable<EnvironmentLog> observable = deviceRuntimeLogModle.sendEnvironmentLog(CO2, O2, Temperature, state);
        deviceRuntimeLogModle.toSubscribe(observable, new RockBaseObserver<EnvironmentLog>(ExperimentPresenter.this, null) {
            @Override
            protected void onBaseNext(EnvironmentLog data) {
                baseView.onRequestEnvironmentLog(data);
            }
        });
    }

    public void cancelScheduleRequestEnvironmentParams() {
        if (disposable_RequestEnvironment != null) {
            disposable_RequestEnvironment.dispose();
            disposable_RequestEnvironment = null;
        }
    }

    //置换计划
    public void scheduleLiquidPlan() {
        List<LiquidLoopPlan> liquidLoopPlanList = liquidLoopPlanDao.queryBuilder()
                                                                   .orderAsc(LiquidLoopPlanDao.Properties.StartTime).list();
        if (liquidLoopPlanList == null || liquidLoopPlanList.size() == 0) {
            return;
        }

        for (LiquidLoopPlan liquidLoopPlan : liquidLoopPlanList) {
            makePlan(liquidLoopPlan);
        }
    }

    private void makePlan(final LiquidLoopPlan liquidLoopPlan) {
        int time = (int) ((liquidLoopPlan.getStartTime().getTime() - new Date().getTime()) / 1000);
        ScheduledFuture scheduledFuture = ScheduleUtil.getInstance().schedule(new Runnable() {
            @Override
            public void run() {
                changeLiquidTask.setLiquidLoopPlan(liquidLoopPlan);
                changeLiquid(liquidLoopPlan.getAmount(), liquidLoopPlan.getFluidIntake_speed(), liquidLoopPlan
                        .getDischard_speed(), LiquidLoopTask.Liquid_medium, null);
            }
        }, time, TimeUnit.SECONDS);
        planScheduledFutureMap.put(liquidLoopPlan, scheduledFuture);
    }

    @Override
    public void requestOpenProject() {
        Observable<Boolean> observable = projectModle.openProject(CartApplication.getInstance().getSystemProjectId());
        projectModle.toSubscribe(observable, new RockBaseObserver<Boolean>(this, null) {
            @Override
            protected void onBaseNext(Boolean data) {
                if (data) {
                    baseView.onRequestOpenProject();
                    isProjectStarted = true;
                } else {
                    baseView.showToast("开启项目失败");
                }
            }
        });
    }

    @Override
    public void requestFinishReclaim() {
        Observable<Boolean> observable = projectModle.finishReclaim(CartApplication.getInstance().getSystemProjectId());
        projectModle.toSubscribe(observable, new RockBaseObserver<Boolean>(this, null) {
            @Override
            protected void onBaseNext(Boolean data) {
                if (data) {
                    baseView.onRequestFinishReclaim();
                } else {
                    baseView.showToast("通知服务器灌装失败");
                }
            }
        });
    }

    //激活液位仪报警功能
    @Override
    void activateLiquidLevelAlarm() {
        if (scheduledLiquidLevel != null && !scheduledLiquidLevel.isCancelled()) {
            return;
        }
        scheduledLiquidLevel = ScheduleUtil.getInstance().scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                liquidLevelModel.readLiquidLevel();
            }
        }, 0, ParamConsts.liquidLevelReadFrequency, TimeUnit.SECONDS);
    }

    @Override
    void stopScheduleReadCO2() {
        if (scheduledCO2 != null) {
            scheduledCO2.cancel(true);
            scheduledCO2 = null;
        }
    }

    @Override
    void stopScheduleReadO2() {
        if (scheduledO2 != null) {
            scheduledO2.cancel(true);
            scheduledO2 = null;
        }
    }

    @Override
    void stopScheduleReadTemperature() {
        if (scheduledTemperature != null) {
            scheduledTemperature.cancel(true);
            scheduledTemperature = null;
        }
    }

    @Override
    void stopActivateLiquidLevelAlarm() {
        if (scheduledLiquidLevel != null) {
            scheduledLiquidLevel.cancel(true);
            scheduledLiquidLevel = null;
        }
    }


    PumpControlModle pumpControlModle = new PumpControlModle();

    @Override
    public void activeDetectPumpFluidIntak() {
        if (scheduledFuturePumpFluidIntake != null && !scheduledFuturePumpFluidIntake.isCancelled()) {
            return;
        }
        scheduledFuturePumpFluidIntake = ScheduleUtil.getInstance().scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                pumpControlModle.readFeedLiquorPump();
            }
        }, 0, ParamConsts.pumpReadFrequency, TimeUnit.MILLISECONDS);
    }

    @Override
    public void activeDetectPumpWaste() {
        if (scheduledFuturePumpWaste != null && !scheduledFuturePumpWaste.isCancelled()) {
            return;
        }
        scheduledFuturePumpWaste = ScheduleUtil.getInstance().scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                pumpControlModle.readWasteLiquorPump();
            }
        }, 0, ParamConsts.pumpReadFrequency, TimeUnit.MILLISECONDS);
    }

    @Override
    public void activeDetectPumpCircling() {
        if (scheduledFuturePumpCircling != null && !scheduledFuturePumpCircling.isCancelled()) {
            return;
        }
        scheduledFuturePumpCircling = ScheduleUtil.getInstance().scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                pumpControlModle.readCirculatingPump();
            }
        }, 0, ParamConsts.pumpReadFrequency, TimeUnit.MILLISECONDS);
    }

    @Override
    public void activeDetectPumpReclaim() {
        if (scheduledFuturePumpReclaim != null && !scheduledFuturePumpReclaim.isCancelled()) {
            return;
        }
        scheduledFuturePumpReclaim = ScheduleUtil.getInstance().scheduleAtFixedRate(() -> pumpControlModle
                .readRecyclingPump(), 0, ParamConsts.pumpReadFrequency, TimeUnit.MILLISECONDS);
    }

    @Override
    public void deActiveDetectPumpFluidIntak() {
        if (scheduledFuturePumpFluidIntake != null) {
            scheduledFuturePumpFluidIntake.cancel(true);
            scheduledFuturePumpFluidIntake = null;
        }
    }

    @Override
    public void deActiveDetectPumpWaste() {
        if (scheduledFuturePumpWaste != null) {
            scheduledFuturePumpWaste.cancel(true);
            scheduledFuturePumpWaste = null;
        }
    }

    @Override
    public void deActiveDetectPumpCircling() {
        if (scheduledFuturePumpCircling != null) {
            scheduledFuturePumpCircling.cancel(true);
            scheduledFuturePumpCircling = null;
        }
    }

    @Override
    public void deActiveDetectPumpReclaim() {
        if (scheduledFuturePumpReclaim != null) {
            scheduledFuturePumpReclaim.cancel(true);
            scheduledFuturePumpReclaim = null;
        }
    }

    @Override
    public void saveOperation(Operation operation) {
        if (operation != null) {
            asyncSession.insert(operation);
        }
    }

    @Override
    public void saveDeviceRecord(DeviceRecord deviceRecord) {
        if (deviceRecord != null) {
            asyncSession.insert(deviceRecord);
        }
    }

    @Override
    public void startShakeTable() {
        valveModle.openShakerValve();
    }

    @Override
    public void stopShakeTable() {
        valveModle.closeShakerValve();
    }

    //检查培养环境是否满足培养条件
    @Override
    String checkCultureEnvironment() {
        StringBuilder checkInfo = new StringBuilder();
        if (currentCO2 == CO2Controller.getInstance().getSettedValue()) {
            checkInfo.append("CO2已达到设定值");
        } else {
            checkInfo.append("当前CO2为" + currentCO2 + "% 设定CO2为" + CO2Controller.getInstance().getSettedValue() + "%");
        }
        checkInfo.append("\n");
        if (currentO2 == O2Controller.getInstance().getSettedValue()) {
            checkInfo.append("O2已达到设定值");
        } else {
            checkInfo.append("当前O2为" + currentCO2 + "% 设定O2为" + O2Controller.getInstance().getSettedValue() + "%");
        }
        checkInfo.append("\n");
        if (currentTemperature == TemperatureController.getInstance().getSettedValue()) {
            checkInfo.append("温度已达到设定值");
        } else {
            checkInfo.append("当前温度为" + currentCO2 + "℃ 设定温度为" + TemperatureController.getInstance().getSettedValue() + "℃");
        }
        checkInfo.append("\n确认开始培养吗?");
        return checkInfo.toString();
    }

    private synchronized boolean isALLPaused() {
        if (inputLiquidTask != null && !inputLiquidTask.isStoped()) {
            return false;
        } else if (wasteTask != null && !wasteTask.isStoped()) {
            return false;
        } else if (reclaimTask != null && !reclaimTask.isStoped()) {
            return false;
        } else if (circleTask != null && !circleTask.isStoped()) {
            return false;
        } else {
            return true;
        }
    }

    private synchronized boolean isALLResumed() {
        if (inputLiquidTask != null && !inputLiquidTask.isRunned() && inputLiquidTask.getState() != OperateTask.STATE_END) {
            return false;
        } else if (wasteTask != null && !wasteTask.isRunned() && wasteTask.getState() != OperateTask.STATE_END) {
            return false;
        } else if (reclaimTask != null && !reclaimTask.isRunned() && reclaimTask.getState() != OperateTask.STATE_END) {
            return false;
        } else if (circleTask != null && !circleTask.isRunned() && circleTask.getState() != OperateTask.STATE_END) {
            return false;
        } else {
            return true;
        }
    }

    //每过24小时后进入下个阶段,直到进入最后一个阶段
    @Override
    public void scheduleExperimentStage() {
        int initDelay;

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        initDelay = (int) ((calendar.getTimeInMillis() - new Date().getTime()) / 1000);

        scheduledFutureExperiment = ScheduleUtil.getInstance().scheduleAtFixedDelay(new Runnable() {
            @Override
            public void run() {
                ExperimentStageManager.getInstance().forwardStage();
                baseView.moveToStage(ExperimentStageManager.getInstance().getCurrentStage());
            }
        }, initDelay, ExperimentStageManager.stageTime, TimeUnit.SECONDS);
    }

    //注入后的冲刷
    @Override
    void scourAfterInjection() {
        isSour = true;
        Operation operation = new Operation();
        operation.setDateTime(new Date());
        operation.setName(Operation.Operate_FluidIntake);
        operation.setData(ParamConsts.scourAfterInjection + "ml");
        operation.setOperator(CartApplication.getInstance().getOperator());
        fluidIntake(ParamConsts.scourAfterInjection, ParamsPreferences.getInstance()
                                                                      .getFluidIntakePumpSpeed(), LiquidLoopTask.Liquid_medium, CartApplication
                .getInstance().getOperator(), new Date(), operation);
    }

    @Override
    String checkFluidIntake() {
        if (inputLiquidTask != null && inputLiquidTask.isDuringTask()) {
            return "已经有进液任务在进行中!请先停止再操作！";
        } else {
            return null;
        }
    }

    private void clearChangeLiquidTask() {
        if (changeLiquidTask != null) {
            if (changeLiquidTask.getInputLiquidTask() != null) {
                changeLiquidTask.getInputLiquidTask().cancelCloseTask();
                //                changeLiquidTask.getInputLiquidTask().clearData();
            }
            if (changeLiquidTask.getWasteTask() != null) {
                changeLiquidTask.getWasteTask().cancelCloseTask();
                //                changeLiquidTask.getWasteTask().clearData();
            }
            changeLiquidTask = null;
        }
    }

    private void changeAir(int time) {
        openCultureTankTask(ParamsPreferences.getInstance().getCultureTankSpeed(), null);
        lastTimeChangeAir = new Date();
        ScheduledFuture scheduledFuture = ScheduleUtil.getInstance().schedule(new Runnable() {
            @Override
            public void run() {
                closeCultureTankTask(null);
            }
        }, time, TimeUnit.SECONDS);
        cultureTankTask.setScheduledFuture(scheduledFuture);
    }

    @Override
    public String checkBeforeFluidIntake() {
        //判断是否已经有进液任务
        //判断是否已经有换液任务
        //判断是否已经有管路清洗任务
        //判断是否已经在进样
        return null;
    }

    public void shakeTable(int second) {
        startShakeTableTask();
        shakeTableTask.setTime(second);
        ScheduledFuture scheduledFuture = ScheduleUtil.getInstance().schedule(new Runnable() {
            @Override
            public void run() {
                closeShakeTableTask();
            }
        }, second, TimeUnit.SECONDS);
        shakeTableTask.setScheduledFuture(scheduledFuture);
    }

    private void startShakeTableTask() {
        if (shakeTableTask == null) {
            shakeTableTask = new ShakeTableTask();
        }
        shakeTableTask.setState(OperateTask.STATE_STARTING);
        startShakeTable();
    }

    private void closeShakeTableTask() {
        if (shakeTableTask != null) {
            shakeTableTask.setState(OperateTask.STATE_ENDING);
        }
        stopShakeTable();
    }

    @Override
    void fluidIntake(int amount, final int speed, final int liquidType, String operator, Date date, final Operation operation) {
        isFluidIntaking = true;

        inputLiquidTask = new LiquidLoopTask(LiquidLoopTask.TASK_FlowSpeed, PeristalticPumpBO.PeristalticPump_fluidIntake);
        inputLiquidTask.setSpeed(speed);
        inputLiquidTask.setDirection(ParamsPreferences.getInstance().getFluidIntakePumpDirection());
        inputLiquidTask.setLiquidType(liquidType);
        inputLiquidTask.setState(LiquidLoopTask.STATE_UNSTART);
        inputLiquidTask.setTotalAmount(amount);
        inputLiquidTask.setOperateDate(date);
        inputLiquidTask.setOperator(operator);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (inputLiquidTask) {
                    if (inputLiquidTask.getLiquidType() == LiquidLoopTask.Liquid_medium) {
                        //培养基进液之前要先摇床摇一下
                        shakeTable(ParamsPreferences.getInstance().getShakeTableTime());
                        inputLiquidTask.setShakeTableTask(shakeTableTask);
                        try {
                            inputLiquidTask.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    if (inputLiquidTask.isTerminate()) {
                        inputLiquidTask.cancelCloseTask();
                        inputLiquidTask = null;
                        if (isChangingLiquid() && changeLiquidTask.isTerminate()) {
                            synchronized (changeLiquidTask) {
                                changeLiquidTask.notifyAll();
                            }
                            baseView.onTerminateChangeLiquid();
                            baseView.setPorgress4Visibility(View.GONE);
                            changeLiquidTask = null;
                        } else {
                            baseView.onTerminateFluidIntaken();
                        }
                        return;
                    }


                    //开阀
                    if (liquidType == LiquidLoopTask.Liquid_medium) {//培养基
                        //关闭生理盐水电磁阀
                        closeSalineValve();
                        openMediumValve();
                    } else if (liquidType == LiquidLoopTask.Liquid_saline) {//生理盐水
                        //生理盐水电磁阀打开
                        openSalineValve();
                        //培养基电磁阀关闭
                        closeMediumValve();
                    } else if (liquidType == LiquidLoopTask.Liquid_cryoprotectant) {//冻存保护液
                        //关闭生理盐水电磁阀
                        closeSalineValve();
                        //关闭培养基电磁阀
                        closeMediumValve();
                    } else if (liquidType == LiquidLoopTask.Liquid_cell) {//细胞
                        //关闭生理盐水电磁阀
                        closeSalineValve();
                        //关闭培养基电磁阀
                        closeMediumValve();
                    } else if (liquidType == LiquidLoopTask.Liquid_viruses) {//病毒
                        //关闭生理盐水电磁阀
                        closeSalineValve();
                        //关闭培养基电磁阀
                        closeMediumValve();
                    }

                    //停止循环泵
                    //                    closePumpTask(PeristalticPumpBO.PeristalticPump_circulating, null);
                    // 停止磁力搅拌器
                    closeStirrerTask(null);

                    saveOperation(operation);

                    //进液
                    //先称重一下,为后面的称重作参考
                    weight();
                    try {
                        inputLiquidTask.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    openPumpTask(PeristalticPumpBO.PeristalticPump_fluidIntake, inputLiquidTask.getSpeed(), inputLiquidTask
                            .getDirection(), null);
                    try {
                        inputLiquidTask.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    closePumpTask(PeristalticPumpBO.PeristalticPump_fluidIntake, null);
                }
            }
        });
        inputLiquidTask.setThread(thread);
        thread.start();
    }

    @Override
    public void terminateFluidIntake() {
        if (inputLiquidTask != null) {
            inputLiquidTask.setTerminate(true);
            if (inputLiquidTask.getShakeTableTask() != null && inputLiquidTask.getShakeTableTask().isRunned()) {
                closeShakeTableTask();
            } else {
                synchronized (inputLiquidTask) {
                    inputLiquidTask.notifyAll();
                }
            }
        }
    }

    @Override
    String checkDischarge() {
        if (wasteTask != null && wasteTask.isDuringTask()) {
            return "已经有排液任务在进行中!请先停止再操作！";
        } else {
            return null;
        }
    }

    @Override
    public String checkBeforeDischage() {
        //判断是否已经有排液任务
        //判断是否已经有换液任务
        //判断是否已经有清洗管路任务
        return null;
    }

    @Override
    void discharge(int amount, final int speed, String operator, Date date, Operation operation) {
        isFluidOutTaking = true;

        //停止循环泵，之前的文档是这么规定
        //        closePumpTask(PeristalticPumpBO.PeristalticPump_circulating, null);
        //打开循环泵，硬件设备需要打开才能排液
        openPumpTask(PeristalticPumpBO.PeristalticPump_circulating, ParamsPreferences.getInstance()
                                                                                     .getCirculatingPumpSpeed(), ParamsPreferences
                .getInstance().getCirculatingPumpDirection(), null);
        //停止磁力搅拌器
        closeStirrerTask(null);

        saveOperation(operation);

        byte direction = ParamsPreferences.getInstance().getWastePumpDirection();
        wasteTask = new LiquidLoopTask(LiquidLoopTask.TASK_FlowSpeed, PeristalticPumpBO.PeristalticPump_waste);
        wasteTask.setSpeed(speed);
        wasteTask.setDirection(direction);
        wasteTask.setState(LiquidLoopTask.STATE_UNSTART);
        wasteTask.setTotalAmount(amount);
        wasteTask.setOperator(operator);
        wasteTask.setOperateDate(date);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (wasteTask) {
                    //先称重一下,为后面的称重作参考
                    weight();
                    try {
                        wasteTask.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    openPumpTask(PeristalticPumpBO.PeristalticPump_waste, wasteTask.getSpeed(), wasteTask
                            .getDirection(), null);
                    try {
                        wasteTask.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    closePumpTask(PeristalticPumpBO.PeristalticPump_waste, null);
                }
            }
        });
        wasteTask.setThread(thread);
        thread.start();
    }

    @Override
    public void terminateDischarge() {
        if (wasteTask != null) {
            wasteTask.setTerminate(true);
            synchronized (wasteTask) {
                wasteTask.notifyAll();
            }
        }
    }

    @Override
    String checkCollect() {
        if (reclaimTask != null && reclaimTask.isDuringTask()) {
            return "已经有收集任务在进行中!请先停止再操作！";
        } else {
            return null;
        }
    }

    @Override
    public String checkBeforeCollect() {
        //判断是否已经有收集任务
        return null;
    }

    @Override
    void collect(int amount, final int speed, String operator, Date date, Operation operation, String collectName) {
        isCollecting = true;

        //关闭其它所有的泵
        closePumpTask(PeristalticPumpBO.PeristalticPump_circulating, null);
        closePumpTask(PeristalticPumpBO.PeristalticPump_fluidIntake, null);
        closePumpTask(PeristalticPumpBO.PeristalticPump_waste, null);

        saveOperation(operation);

        //        clearAllProgress();

        byte direction = ParamsPreferences.getInstance().getWastePumpDirection();
        reclaimTask = new LiquidLoopTask(LiquidLoopTask.TASK_FlowSpeed, PeristalticPumpBO.PeristalticPump_reclaim);
        reclaimTask.setSpeed(speed);
        reclaimTask.setDirection(direction);
        reclaimTask.setState(LiquidLoopTask.STATE_UNSTART);
        reclaimTask.setTotalAmount(amount);
        reclaimTask.setOperator(operator);
        reclaimTask.setOperateDate(date);
        reclaimTask.setCollectName(collectName);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (reclaimTask) {
                    //先称重一下,为后面的称重作参考
                    weight();
                    try {
                        reclaimTask.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    openPumpTask(PeristalticPumpBO.PeristalticPump_reclaim, reclaimTask.getSpeed(), reclaimTask
                            .getDirection(), null);
                    try {
                        reclaimTask.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    closePumpTask(PeristalticPumpBO.PeristalticPump_reclaim, null);
                }
            }
        });
        reclaimTask.setThread(thread);
        thread.start();
    }

    @Override
    public void terminateCollect() {
        if (reclaimTask != null) {
            reclaimTask.setTerminate(true);
            synchronized (reclaimTask) {
                reclaimTask.notifyAll();
            }
        }
    }

    @Override
    public void terminateCircle() {
        if (circleTask != null) {
            circleTask.setTerminate(true);
            closePumpTask(PeristalticPumpBO.PeristalticPump_circulating, null);
        }
    }

    @Override
    String checkChangeLiquid() {
        //换液涉及到2个蠕动泵
        StringBuilder err = new StringBuilder();
        String err_discharge = checkDischarge();
        if (err_discharge != null) {
            err.append(err_discharge);
        }
        String err_fluidIntake = checkFluidIntake();
        if (err_fluidIntake != null) {
            if (err.length() != 0) {
                err.append("\n");
            }
            err.append(err_fluidIntake);
        }
        return err.length() == 0 ? null : err.toString();
    }

    @Override
    public String checkBeforeChangeLiquid() {
        //判断是否已经有换液任务
        //判断是否已经有进液任务
        //判断是否已经有排液任务
        //判断是否已经有进样任务
        //判断是否已经有清洗管路任务
        return null;
    }

    @Override
    void changeLiquid(int amount, int fluidIntakeSpeed, int wasteSpeed, int liquidType, Operation operation) {
        saveOperation(operation);

        clearChangeLiquidTask();
        //        clearAllProgress();
        //        isChangeLiquid=true;
        changeLiquidTask = new ChangeLiquidTask(amount);
        changeLiquidTask.setState(OperateTask.STATE_STARTING);
        changeLiquidTask.setFluidSpeed(fluidIntakeSpeed);
        changeLiquidTask.setWasteSpeed(wasteSpeed);
        changeLiquidTask.setLiquidType(liquidType);
        //先排液，排完之后再进液
        discharge(amount, wasteSpeed, "系统", new Date(), null);
        changeLiquidTask.setWasteTask(wasteTask);
    }

    @Override
    void changeLiquid(final ChangeLiquidBO changeLiquidBO, Date operateDate, String operator) {
        clearChangeLiquidTask();

        changeLiquidTask = new ChangeLiquidTask();
        changeLiquidTask.setOperateDate(operateDate);
        changeLiquidTask.setOperator(operator);
        changeLiquidTask.setState(OperateTask.STATE_STARTING);
        changeLiquidTask.setFluidSpeed(ParamsPreferences.getInstance().getFluidIntakePumpSpeed());
        changeLiquidTask.setWasteSpeed(ParamsPreferences.getInstance().getWastePumpSpeed());
        changeLiquidTask.setChangeLiquidBO(changeLiquidBO);
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (changeLiquidTask) {
                    for (int turn = 1; turn <= changeLiquidTask.getTotalTurn(); turn++) {
                        while (changeLiquidTask.getCurrentChangeIndex() < changeLiquidTask.getTotalTimes(turn)) {
                            int index = changeLiquidTask.getCurrentChangeIndex() + 1;
                            //如果置换体积为0则不置换
                            if (changeLiquidTask.getChangeLiquidBO()
                                                .getFluidAmountByTurnIndex(turn, index) == 0 && changeLiquidTask
                                    .getChangeLiquidBO().getWasteAmountByTurnIndex(turn, index) == 0) {
                                break;
                            }
                            runChangeLiquid(turn, index, changeLiquidBO.getFluidTypeTurnIndex(turn, index));
                            try {
                                changeLiquidTask.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            if (changeLiquidTask == null || changeLiquidTask.isTerminate()) {
                                return;
                            }
                        }
                        //一轮结束，新一轮还是从0开始
                        changeLiquidTask.setCurrentChangeIndex(0);
                        int sleepTime = changeLiquidTask.getChangeLiquidBO().getIntervalTimeByTurn(turn) * 1000;
                        if (sleepTime > 0) {
                            try {
                                Thread.sleep(sleepTime);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        if (changeLiquidTask == null || changeLiquidTask.isTerminate()) {
                            return;
                        }
                    }
                }
                if (changeLiquidTask.getLiquidLoopPlan() != null) {
                    finishLiquidPlan(changeLiquidTask.getLiquidLoopPlan());
                }
                changeLiquidTask = null;
                baseView.runOnUi(new Runnable() {
                    @Override
                    public void run() {
                        baseView.onChangeLiquidSucc();
                        baseView.stopChangeLiquidProgressBar();
                    }
                });
            }
        });
        changeLiquidTask.setThread(thread);
        thread.start();
    }

    @Override
    public void terminateChangeLiquid() {
        changeLiquidTask.setTerminate(true);
        terminateDischarge();
        terminateFluidIntake();
    }

    @Override
    void editChangeLiquid(ChangeLiquidBO changeLiquidBO) {

    }

    private void runChangeLiquid(int turn, int index, int fluidType) {
        if (changeLiquidTask == null || changeLiquidTask.getChangeLiquidBO() == null || changeLiquidTask
                .getTotalTurn() < turn || changeLiquidTask.getTotalTimes(turn) < index) {
            return;
        }
        int amount = changeLiquidTask.getWasteAmount(turn, index);
        //先排液，排完之后再进液
        discharge(amount, ParamsPreferences.getInstance().getWastePumpSpeed(), "系统", new Date(), null);
        changeLiquidTask.setWasteTask(wasteTask);
        changeLiquidTask.setCurrentChangeTurn(turn);
        changeLiquidTask.setCurrentChangeIndex(index);
        changeLiquidTask.setLiquidType(fluidType);

        Operation operation = new Operation();
        operation.setName(Operation.Operate_ChangeLiquid);
        operation.setDateTime(new Date());
        operation.setOperator(CartApplication.getInstance().getOperator());
        String data = String.format("第%d轮第%d次置换，体积%dml", turn, index, amount);
        operation.setData(data);
        RockToast.showToastSafe(data);
        saveOperation(operation);
    }

    //生理盐水置换培养基
    @Override
    public void changeLiquidWithSaline() {

    }

    //添加冻存保护剂
    @Override
    public void addCryoprotectant() {

    }

    @Override
    public ChangeLiquidBO getChangeLiquidBO() {
        if (changeLiquidTask == null) {
            return null;
        } else {
            return changeLiquidTask.getChangeLiquidBO();
        }
    }

    @Override
    boolean isChangingLiquid() {
        return changeLiquidTask != null;
    }

    boolean isCleanPipes() {
        return isCleanPipes && cleanPipesTask != null;
    }

    private void loopLiquid(int loopTime, int speed) {
        //        clearAllProgress();

        //        int speed = ParamsPreferences.getInstance().getCirculatingPumpSpeed();
        byte direction = ParamsPreferences.getInstance().getCirculatingPumpDirection();
        circleTask = new LiquidLoopTask(LiquidLoopTask.TASK_TimeSpeed, PeristalticPumpBO.PeristalticPump_circulating);
        circleTask.setSpeed(speed);
        circleTask.setDirection(direction);
        circleTask.setState(LiquidLoopTask.STATE_STARTING);
        circleTask.setTime(loopTime);

        circleTask.setTime(loopTime);
        ScheduledFuture scheduledFuture = ppOperate(PeristalticPumpBO.PeristalticPump_circulating, speed, loopTime, direction);
        circleTask.setScheduledFuture(scheduledFuture);
    }

    //----------------------------------------------------------------------------------------------
    @Override
    public void saveInjectionData(Injection injection) {
        //        Injection injection = new Injection(null, ProjectManager.getInstance().getProjectId(),ExperimentStageManager.getInstance().getStageId(), operator, startDate,finishDate, name, amount);
        asyncSession.insert(injection);
    }

    @Override
    public void saveSampleData(Sample sample) {
        //        Sample sample = new Sample(null, ProjectManager.getInstance().getProjectId(),ExperimentStageManager.getInstance().getStageId(), operator, startDate,finishDate, countType, count);
        asyncSession.insert(sample);
    }

    //----------------------------------------------------------------------------------------------

    //    private void clearAllProgress() {
    //        if (fluidIntakDisposable != null && !fluidIntakDisposable.isDisposed()) {
    //            fluidIntakDisposable.dispose();
    //        }
    //        if (fluidOutDisposable != null && !fluidOutDisposable.isDisposed()) {
    //            fluidOutDisposable.dispose();
    //        }
    //        if (collectDisposable != null && !collectDisposable.isDisposed()) {
    //            collectDisposable.dispose();
    //        }
    //        baseView.clearAllProgress();
    //    }

    @Override
    public synchronized boolean isReadyForInject() {
        //关闭生理盐水电磁阀
        if (SalineValveController.getInstance().getStatus() != ValveBO.close) {
            return false;
        }
        //关闭培养基电磁阀
        if (MediumValveController.getInstance().getStatus() != ValveBO.close) {
            return false;
        }
        //停止循环泵
        if (CirculatingPumpController.getInstance().getSpeed() != 0) {
            return false;
        }
        //停止磁力搅拌器
        if (MagneticStirrerController.getInstance().getSpeed() != 0) {
            return false;
        }
        //打开进液泵
        if (FluidIntakePumpController.getInstance().getSpeed() == 0) {
            return false;
        }
        return true;
    }

    @Override
    public synchronized boolean isReadyForSample() {
        //打开循环泵
        if (CirculatingPumpController.getInstance().getSpeed() == 0) {
            return false;
        }
        return true;
    }

    @Override
    public void openSalineValve() {
        valveModle.openSalineValve();
    }

    @Override
    public void closeSalineValve() {
        valveModle.closeSalineValve();
    }

    @Override
    public void openMediumValve() {
        valveModle.openMediumValve();
    }

    @Override
    public void closeMediumValve() {
        valveModle.closeMediumValve();
    }

    @Override
    void openPumpTask(byte modularNO, int speed, byte direction, Operation operation) {
        //是否要先关闭
        boolean needClose = false;
        LiquidLoopTask liquidLoopTask = getLiquidTaskByModularNO(modularNO);
        BasePumpController pumpController = getPumpCpntroller(modularNO);
        if (liquidLoopTask != null) {
            if (liquidLoopTask.isRunned()) {
                liquidLoopTask.cancelCloseTask();

                if (pumpController.isDirectionChange(direction)) {
                    needClose = true;
                }
                liquidLoopTask.setChangingDirection(true);
            } else {
                liquidLoopTask.setChangingDirection(false);
            }
        } else {
            liquidLoopTask = createLiquidTaskByModularNO(LiquidLoopTask.TASK_Speed, modularNO);
        }
        //        clearAllProgress();

        pumpController.setSettingDirection(direction);
        pumpController.setSettingSpeed(speed);

        liquidLoopTask.setTaskType(LiquidLoopTask.TASK_Speed);
        liquidLoopTask.setState(OperateTask.STATE_STARTING);
        liquidLoopTask.setSpeed(speed);
        //        liquidLoopTask.setOperation(operation);
        if (needClose) {//改变方向需要先关闭再启动
            closePump(modularNO);
        }
        openPump(modularNO, speed, direction);
        saveOperation(operation);
    }

    //停止蠕动泵，同时取消之后的停止任务，以防冲突。
    @Override
    void closePumpTask(byte modularNO, Operation operation) {
        //        if(isTesting){
        //            closePump(modularNO);
        //            return;
        //        }
        LiquidLoopTask liquidLoopTask = getLiquidTaskByModularNO(modularNO);
        if (liquidLoopTask != null) {
            liquidLoopTask.cancelCloseTask();
            //            liquidLoopTask.clearData();
            liquidLoopTask.setState(OperateTask.STATE_ENDING);
            //设置新的操作
            //            liquidLoopTask.setOperation(operation);
        }
        closePump(modularNO);
    }

    @Override
    void openStirrerTask(int speed, DeviceRecord deviceRecord) {
        if (stirrerTask != null && stirrerTask.isRunned()) {
            //            baseView.onError("此设备有未完成的运行任务");
            stirrerTask.cancelCloseTask();
            //            baseView.showToast("新任务");
        }
        if (stirrerTask == null) {
            stirrerTask = new StirrerTask(speed);
        }
        stirrerTask.setState(OperateTask.STATE_STARTING);
        stirrerTask.setSpeed(speed);
        stirrerTask.setStartSpeed(MagneticStirrerController.getInstance().getSpeed());
        if (stirrerTask.getSpeed() == stirrerTask.getStartSpeed()) {
            openStirrer(speed);
        } else {
            int speedAdjust = speed - stirrerTask.getStartSpeed();
            int take = Math.abs(speedAdjust / 10);
            if (speedAdjust % 10 != 0) {
                take++;
            }
            Log.i("stirrerTask", "take:" + take);
            //磁力搅拌器启动时，每秒加10转，慢慢的启动。若降速，速度也每秒降10转，慢慢降速。
            Disposable disposable = Observable.interval(0, 1, TimeUnit.SECONDS).take(take).subscribeOn(Schedulers.io())
                                              .map(new Function<Long,Integer>() {
                                                  @Override
                                                  public Integer apply(Long aLong) throws Exception {
                                                      int addSpeed = (int) ((aLong + 1) * 10);
                                                      int speed;
                                                      if (stirrerTask.getSpeed() > stirrerTask.getStartSpeed()) {//提速
                                                          speed = stirrerTask.getStartSpeed() + addSpeed;
                                                          if (speed > stirrerTask.getSpeed()) {
                                                              speed = stirrerTask.getSpeed();
                                                          }
                                                      } else if (stirrerTask.getSpeed() < stirrerTask.getStartSpeed()) {//降速
                                                          speed = stirrerTask.getStartSpeed() - addSpeed;
                                                          if (speed < stirrerTask.getSpeed()) {
                                                              speed = stirrerTask.getSpeed();
                                                          }
                                                      } else {
                                                          speed = stirrerTask.getStartSpeed();
                                                      }
                                                      return speed;
                                                  }
                                              }).subscribe(new Consumer<Integer>() {
                        @Override
                        public void accept(Integer integer) throws Exception {
                            Log.i("stirrerTask", "speed:" + integer);
                            openStirrer(integer);
                        }
                    });
            stirrerTask.setDisposable(disposable);
            //            openStirrer(speed);
        }
        saveDeviceRecord(deviceRecord);
    }

    @Override
    void closeStirrerTask(DeviceRecord deviceRecord) {
        if (stirrerTask != null) {
            stirrerTask.setState(OperateTask.STATE_ENDING);
        }
        closeStirrer();
        saveDeviceRecord(deviceRecord);
    }

    @Override
    void openUltravioletLightTask() {
        if (ultravioletLightTask == null) {
            ultravioletLightTask = new UltravioletLightTask();
        }
        ultravioletLightTask.setState(OperateTask.STATE_STARTING);
        openUltravioletLight();
    }

    @Override
    void closeUltravioletLightTask() {
        if (ultravioletLightTask != null) {
            ultravioletLightTask.setState(OperateTask.STATE_ENDING);
        }
        closeUltravioletLight();
    }

    @Override
    void openCultureTankTask(int speed, DeviceRecord deviceRecord) {
        if (cultureTankTask == null) {
            cultureTankTask = new CultureTankTask(speed);
        }
        cultureTankTask.setState(OperateTask.STATE_STARTING);
        openCultureTank(speed);
        saveDeviceRecord(deviceRecord);
    }

    @Override
    void closeCultureTankTask(DeviceRecord deviceRecord) {
        if (cultureTankTask != null) {
            cultureTankTask.setState(OperateTask.STATE_ENDING);
        }
        closeCultureTank();
        saveDeviceRecord(deviceRecord);
    }

    @Override
    void openIncubatorTask() {
        if (incubatorTask == null) {
            incubatorTask = new IncubatorTask();
        }
        incubatorTask.setState(OperateTask.STATE_STARTING);
        openIncubator();
    }

    @Override
    void closeIncubatorTask() {
        if (incubatorTask != null) {
            incubatorTask.setState(OperateTask.STATE_ENDING);
        }
        closeIncubator();
    }

    @Override
    void startNewProject() {
        isStartNewProject = true;
        //        cancelAllTask();
        //        closeAllDevices();
        ProjectManager.getInstance().restartProject();
        baseView.onStartNewProject();
    }

    @Override
    public boolean isScheduleTaskClose() {
        if (scheduledCO2 != null) {
            //            err.append("CO2检查任务未停止\n");
            return false;
        }
        if (scheduledO2 != null) {
            //            err.append("O2检查任务未停止\n");
            return false;
        }
        if (scheduledTemperature != null) {
            //            err.append("温度检查任务未停止\n");
            return false;
        }
        if (scheduledLiquidLevel != null) {
            //            err.append("液位仪检查任务未停止\n");
            return false;
        }
        return true;
    }

    public void cancelAllTask() {
        stopScheduleReadCO2();
        stopScheduleReadO2();
        stopScheduleReadTemperature();
        stopScheduleWeight();
        stopActivateLiquidLevelAlarm();
        cancelScheduleRequestEnvironmentParams();
    }

    //检查是否所有设备关闭，所有任务结束，准备好开始新的细胞培养项目
    private String isReadyForNewProject() {
        StringBuilder err = new StringBuilder();
        if (scheduledCO2 != null) {
            err.append("CO2检查任务未停止\n");
        }
        if (scheduledO2 != null) {
            err.append("O2检查任务未停止\n");
        }
        if (scheduledTemperature != null) {
            err.append("温度检查任务未停止\n");
        }
        if (scheduledLiquidLevel != null) {
            err.append("液位仪检查任务未停止\n");
        }
        if (inputLiquidTask != null && inputLiquidTask.isRunned()) {
            err.append("进液泵未停止\n");
        }
        if (wasteTask != null && wasteTask.isRunned()) {
            err.append("废液泵未停止\n");
        }
        if (circleTask != null && circleTask.isRunned()) {
            err.append("循环泵未停止\n");
        }
        if (reclaimTask != null && reclaimTask.isRunned()) {
            err.append("罐装泵未停止\n");
        }
        if (stirrerTask != null && stirrerTask.isRunned()) {
            err.append("磁力搅拌器未停止\n");
        }
        if (cultureTankTask != null && cultureTankTask.isRunned()) {
            err.append("培养罐换气泵未停止\n");
        }
        if (incubatorTask != null && incubatorTask.isRunned()) {
            err.append("培养箱换气泵未停止\n");
        }
        if (ultravioletLightTask != null && ultravioletLightTask.isRunned()) {
            err.append("紫外线灯未停止\n");
        }
        return err.length() == 0 ? null : err.toString();
    }

    @Override
    public void stopAllOperate() {
        closePumpTask(PeristalticPumpBO.PeristalticPump_fluidIntake, null);
        closePumpTask(PeristalticPumpBO.PeristalticPump_waste, null);
        closePumpTask(PeristalticPumpBO.PeristalticPump_circulating, null);
        closePumpTask(PeristalticPumpBO.PeristalticPump_reclaim, null);
        closeCultureTankTask(null);
        closeStirrerTask(null);
        closeUltravioletLightTask();
        closeHeat();
        closeCO2();
        closeO2();
        closeMediumValve();
        closeSalineValve();
        closeDoor();
    }

    //--------------------直接操作设备--------------------------------------------------------------
    //    @Override
    private void openPump(byte modularNO, int speed, byte direction) {
        String err = checkBeforeOperate();
        if (err != null) {
            baseView.onError(err);
            return;
        }
        peristalticPumpModle.openPeristaltic_pump(modularNO, speed, direction);
    }

    //    @Override
    private void closePump(byte modularNO) {
        peristalticPumpModle.closePeristaltic_pump(modularNO);
    }

    //    @Override
    private void openStirrer(int speed) {
        String err = checkBeforeOperate();
        if (err != null) {
            baseView.onError(err);
            return;
        }
        magneticStirrerModel.openMagneticStirrer(speed);
    }

    //    @Override
    private void closeStirrer() {
        magneticStirrerModel.closeMagneticStirrer();
    }

    //    @Override
    private void openUltravioletLight() {
        ultravioletLightModle.open();
    }

    //    @Override
    private void closeUltravioletLight() {
        ultravioletLightModle.close();
    }

    public void openCultureTank(int speed) {
        cultureTankModle.openMagneticStirrer(speed);
    }

    public void closeCultureTank() {
        cultureTankModle.closeMagneticStirrer();
    }

    private void openIncubator() {
        incubatorModle.openMagneticStirrer();
    }

    private void closeIncubator() {
        incubatorModle.closeMagneticStirrer();
    }

    @Override
    void setCO2(double co2) {
        co2Modle.setCO2(co2);
    }

    @Override
    void setO2(double o2) {
        o2Modle.setO2(o2);
    }

    @Override
    void setTemperature(double temperature) {
        temperatureModle.setTemperature(temperature);
    }

    @Override
    public void ReadTemperature() {
        temperatureModle.readTemperature();
    }

    @Override
    public void ReadO2() {
        o2Modle.readO2();
    }

    @Override
    public void ReadCO2() {
        co2Modle.readCO2();
    }

    @Override
    void peel(byte[] ad) {
        electronicScaleModle.peel(ad);
    }

    @Override
    void weight() {
        electronicScaleModle.weight();
    }

    @Override
    void openDoor() {
        doorModle.open();
    }

    @Override
    void closeDoor() {
        doorModle.close();
    }

    @Override
    public void readDoor() {
        doorModle.read();
    }

    @Override
    public void stopDoor() {
        doorModle.stop();
    }

    @Override
    public void closeHeat() {
        temperatureModle.closeHeat();
    }

    @Override
    public void closeCO2() {
        co2Modle.closeCO2();
    }

    @Override
    public void closeO2() {
        o2Modle.closeO2();
    }

    //----------------------------------------------------------------------------------------------


    @Override
    public double getLeftTime(byte modularNO) {
        LiquidLoopTask liquidLoopTask = getLiquidTaskByModularNO(modularNO);
        if (liquidLoopTask != null) {
            return liquidLoopTask.getLeftTimeAfterPause();
        } else {
            return 0;
        }
    }

    @Override
    boolean isPumpStoped(byte ModularNo) {
        LiquidLoopTask liquidLoopTask = getLiquidTaskByModularNO(ModularNo);
        //        if(liquidLoopTask!=null&&liquidLoopTask.getPeristalticPumpBO()!=null){
        //            return liquidLoopTask.getPeristalticPumpBO().getOrder();
        //        }
        //        return 0;
        if (liquidLoopTask == null) {
            return true;
        } else {
            return !liquidLoopTask.isRunned();
        }
        //        return 0;
    }

    @Override
    boolean isPumpPaused(byte ModularNo) {
        LiquidLoopTask liquidLoopTask = getLiquidTaskByModularNO(ModularNo);
        if (liquidLoopTask == null) {
            return false;
        }
        return liquidLoopTask.getState() == LiquidLoopTask.STATE_PAUSE;
    }

    @Override
    boolean isPumpRunned(byte ModularNo) {
        LiquidLoopTask liquidLoopTask = getLiquidTaskByModularNO(ModularNo);
        if (liquidLoopTask == null) {
            return false;
        }
        return liquidLoopTask.isRunned();
    }

    @Override
    public int getFluidIntakenStatus() {
        if (inputLiquidTask == null) {
            return OperateTask.STATE_UNSTART;
        } else {
            return inputLiquidTask.getState();
        }
    }

    @Override
    public int getWasteStatus() {
        if (wasteTask == null) {
            return OperateTask.STATE_UNSTART;
        } else {
            return wasteTask.getState();
        }
    }

    @Override
    public int getCirclingStatus() {
        if (circleTask == null) {
            return OperateTask.STATE_UNSTART;
        } else {
            return circleTask.getState();
        }
    }

    @Override
    public int getReclaimStatus() {
        if (reclaimTask == null) {
            return OperateTask.STATE_UNSTART;
        } else {
            return reclaimTask.getState();
        }
    }

    @Override
    public int getChangeLiquidStatus() {
        if (changeLiquidTask == null) {
            return OperateTask.STATE_UNSTART;
        } else {
            return changeLiquidTask.getState();
        }
    }

    //----------------------------------------------------------------------------------------------
    private LiquidLoopTask getLiquidTaskByModularNO(byte modularNO) {
        if (modularNO == PeristalticPumpBO.PeristalticPump_fluidIntake) {
            return inputLiquidTask;
        } else if (modularNO == PeristalticPumpBO.PeristalticPump_circulating) {
            return circleTask;
        } else if (modularNO == PeristalticPumpBO.PeristalticPump_waste) {
            return wasteTask;
        } else if (modularNO == PeristalticPumpBO.PeristalticPump_reclaim) {
            return reclaimTask;
        } else {
            return null;
        }
    }

    private BasePumpController getPumpCpntroller(byte modularNO) {
        if (modularNO == PeristalticPumpBO.PeristalticPump_fluidIntake) {
            return FluidIntakePumpController.getInstance();
        } else if (modularNO == PeristalticPumpBO.PeristalticPump_circulating) {
            return CirculatingPumpController.getInstance();
        } else if (modularNO == PeristalticPumpBO.PeristalticPump_waste) {
            return WastePumpController.getInstance();
        } else if (modularNO == PeristalticPumpBO.PeristalticPump_reclaim) {
            return ReclaimPumpController.getInstance();
        } else {
            return null;
        }
    }

    private LiquidLoopTask createLiquidTaskByModularNO(int taskType, byte modularNO) {
        if (modularNO == PeristalticPumpBO.PeristalticPump_fluidIntake) {
            inputLiquidTask = new LiquidLoopTask(taskType, modularNO);
            return inputLiquidTask;
        } else if (modularNO == PeristalticPumpBO.PeristalticPump_circulating) {
            circleTask = new LiquidLoopTask(taskType, modularNO);
            return circleTask;
        } else if (modularNO == PeristalticPumpBO.PeristalticPump_waste) {
            wasteTask = new LiquidLoopTask(taskType, modularNO);
            return wasteTask;
        } else if (modularNO == PeristalticPumpBO.PeristalticPump_reclaim) {
            reclaimTask = new LiquidLoopTask(taskType, modularNO);
            return reclaimTask;
        } else {
            return null;
        }

    }

    public void pausePeristalticPump(byte modularNO) {
        LiquidLoopTask liquidLoopTask = getLiquidTaskByModularNO(modularNO);
        if (liquidLoopTask == null) {
            //            baseView.showToast("没有任务");
            return;
        }
        //        if(liquidLoopTask.getTaskType()==LiquidLoopTask.TASK_Speed){
        ////            baseView.showToast("没有设定流量或者时间，请按关");
        //            return;
        //        }
        liquidLoopTask.setState(LiquidLoopTask.STATE_PAUSEING);
        //        if(liquidLoopTask.getScheduledFuture()!=null){
        //            liquidLoopTask.getScheduledFuture().cancel(true);
        //            liquidLoopTask.setScheduledFuture(null);
        //        }
        closePump(modularNO);
    }

    public void resumePeristalticPump(byte modularNO) {
        LiquidLoopTask liquidLoopTask = getLiquidTaskByModularNO(modularNO);
        if (liquidLoopTask == null) {
            return;
        }
        if (liquidLoopTask.getTaskType() == LiquidLoopTask.TASK_Speed) {
            liquidLoopTask.setState(LiquidLoopTask.STATE_RESUMEING);
            openPump(liquidLoopTask.getModularNO(), liquidLoopTask.getSpeed(), liquidLoopTask.getDirection());
        } else {
            double time = liquidLoopTask.getTime();
            double runnedTime = (double) (liquidLoopTask.getPauseTime().getTime() - liquidLoopTask.getStartTime()
                                                                                                  .getTime()) / 1000;
            double leftTime = time - runnedTime;
            liquidLoopTask.setState(LiquidLoopTask.STATE_RESUMEING);
            liquidLoopTask.setStartTime(new Date());
            liquidLoopTask.setTime(leftTime);
            ScheduledFuture scheduledFuture = ppOperate(liquidLoopTask.getModularNO(), liquidLoopTask.getSpeed(), (int) Math
                    .round(leftTime), liquidLoopTask.getDirection());
            liquidLoopTask.setScheduledFuture(scheduledFuture);
        }
    }

    //报警解除之后的恢复，设备会自动恢复运转，不需要发送命令
    private void resumePumpAfterAlarmDismiss(final byte modularNO) {
        LiquidLoopTask liquidLoopTask = getLiquidTaskByModularNO(modularNO);
        if (liquidLoopTask == null) {
            return;
        }
        if (liquidLoopTask.getTaskType() == LiquidLoopTask.TASK_Speed) {
            liquidLoopTask.setState(LiquidLoopTask.STATE_RESUMED);
            //            openPump(liquidLoopTask.getModularNO(),liquidLoopTask.getSpeed(),liquidLoopTask.getDirection());
        } else {
            double time = liquidLoopTask.getTime();
            double runnedTime = (double) (liquidLoopTask.getPauseTime().getTime() - liquidLoopTask.getStartTime()
                                                                                                  .getTime()) / 1000;
            double leftTime = time - runnedTime;
            liquidLoopTask.setState(LiquidLoopTask.STATE_RESUMED);
            liquidLoopTask.setTime(leftTime);
            liquidLoopTask.setStartTime(new Date());
            //            ScheduledFuture scheduledFuture = ppOperate(liquidLoopTask.getModularNO(), liquidLoopTask.getSpeed(), (int) Math.round(leftTime), liquidLoopTask.getDirection());
            ScheduledFuture scheduledFuture = ScheduleUtil.getInstance().schedule(new Runnable() {
                @Override
                public void run() {
                    closePumpTask(modularNO, null);
                    //                peristalticPumpModle.closePeristaltic_pump(modularNO);
                }
            }, (int) Math.round(leftTime), TimeUnit.SECONDS);
            liquidLoopTask.setScheduledFuture(scheduledFuture);
        }
    }

    public void endPeristalticPump(byte modularNO) {
        LiquidLoopTask liquidLoopTask = getLiquidTaskByModularNO(modularNO);
        if (liquidLoopTask == null) {
            return;
        }
        liquidLoopTask.setState(OperateTask.STATE_ENDING);
        closePump(modularNO);
    }

    @Override
    public void editAmountForPausedTask(byte modularNO, int amount) {
        LiquidLoopTask liquidLoopTask = getLiquidTaskByModularNO(modularNO);
        if (liquidLoopTask == null) {
            return;
        }
        if (liquidLoopTask.getTaskType() == LiquidLoopTask.TASK_Speed) {
            liquidLoopTask.setState(LiquidLoopTask.STATE_RESUMEING);
            openPump(liquidLoopTask.getModularNO(), liquidLoopTask.getSpeed(), liquidLoopTask.getDirection());
        } else {
            int leftTime = (int) Math.round(UtilHelpers.calculateTimeBySpeedFlow(liquidLoopTask.getSpeed(), amount));

            //            int time = liquidLoopTask.getTime();
            //            int runnedTime = (int) ((liquidLoopTask.getPauseTime().getTime() - liquidLoopTask.getStartTime().getTime()) / 1000);
            //            int leftTime = time - runnedTime;

            liquidLoopTask.setState(LiquidLoopTask.STATE_RESUMEING);
            liquidLoopTask.setTime(leftTime);
            ScheduledFuture scheduledFuture = ppOperate(liquidLoopTask.getModularNO(), liquidLoopTask
                    .getSpeed(), leftTime, liquidLoopTask.getDirection());
            liquidLoopTask.setScheduledFuture(scheduledFuture);
        }
    }

    private ScheduledFuture ppOperate(final byte modularNO, int speed, int time, byte direction) {
        peristalticPumpModle.openPeristaltic_pump(modularNO, speed, direction);
        ScheduledFuture scheduledFuture = ScheduleUtil.getInstance().schedule(new Runnable() {
            @Override
            public void run() {
                closePumpTask(modularNO, null);
                //                peristalticPumpModle.closePeristaltic_pump(modularNO);
            }
        }, time, TimeUnit.SECONDS);
        return scheduledFuture;
    }

    //液位异常时停止进液泵
    @Override
    void onLiquidLevelError() {
        if (inputLiquidTask != null && inputLiquidTask.isDuringTask()) {
            pausePeristalticPump(PeristalticPumpBO.PeristalticPump_fluidIntake);
        } else {
            //            Operation operation=new Operation();
            //            operation.setName("停止进液泵");
            //            operation.setData("液位异常");
            DeviceRecord deviceRecord = new DeviceRecord();
            deviceRecord.setName("停止进液泵");
            deviceRecord.setDevice("进液泵");
            deviceRecord.setData("液位异常");
            closePumpTask(PeristalticPumpBO.PeristalticPump_fluidIntake, null);
        }
    }

    //如果遇到某些异常情况，则不能操作
    private String checkBeforeOperate() {
        //        String err=null;
        //        if(levelLiquid_warning>=3){
        //            err="液位仪检测到异常";
        //        }
        //        return err;
        //测试
        return null;
    }

    private synchronized boolean isStartCultureSucc() {
        if (CirculatingPumpController.getInstance().getSpeed() == 0) {
            return false;
        } else if (MagneticStirrerController.getInstance().getSpeed() == 0) {
            return false;
        } else if (CultureTankController.getInstance().getSpeed() > 0) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public int getCurrentLiquidInTank() {
        return ParamConsts.currentCultureTankLiquid;
    }

    private void addTankLiquid(int amount) {
        ParamConsts.currentCultureTankLiquid += amount;
    }

    private boolean isTankLiquidFull() {
        if (ParamConsts.currentCultureTankLiquid >= ParamConsts.cultureTankVolume) {
            return true;
        } else {
            return false;
        }
    }

    //判断培养罐中的液体是否快要满了需要报警。
    private boolean isTankLiquidNeedWarning() {
        if (ParamConsts.currentCultureTankLiquid + 100 >= ParamConsts.cultureTankVolume) {
            return true;
        } else {
            return false;
        }
    }

    //----------------------------------------------------------------------------------------------
    //测试
    //    @Subscribe(threadMode = ThreadMode.MAIN)
    //    public void onMessageEvent(ChangeAirEvent event) {
    //        cancelScheduleChangeAir();
    //        if (!cultureTankTask.isRunned()) {
    //            int diff = (int) (((event.getFrequency() * 1000) - (new Date().getTime() - lastTimeChangeAir.getTime())) / 1000);
    //            if (diff < 0) {
    //                diff = 0;
    //            }
    //            scheduleChangeAir(diff);
    //        } else {
    //            //重新设置换气
    //            scheduleChangeAir(event.getFrequency());
    //        }
    //    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LiquidLoopPlanEvent event) {
        if (event == null) {
            return;
        }
        if (event.getEvent() == LiquidLoopPlanEvent.evetn_delete) {
            planScheduledFutureMap.remove(event);
        } else if (event.getEvent() == LiquidLoopPlanEvent.evetn_add) {
            makePlan(event.getLiquidLoopPlan());
        } else if (event.getEvent() == LiquidLoopPlanEvent.evetn_edit) {
            planScheduledFutureMap.remove(event);
            makePlan(event.getLiquidLoopPlan());
        }
    }

    @Override
    public void onCommandReceive(BaseBO baseBO) {
        if (baseBO instanceof PeristalticPumpBO) {
            onMessageEvent((PeristalticPumpBO) baseBO);
        } else if (baseBO instanceof MagneticStirrerBO) {
            onMessageEvent((MagneticStirrerBO) baseBO);
        } else if (baseBO instanceof CultureTankBO) {
            onMessageEvent((CultureTankBO) baseBO);
        } else if (baseBO instanceof IncubatorBO) {
            onMessageEvent((IncubatorBO) baseBO);
        } else if (baseBO instanceof CO2BO) {
            onMessageEvent((CO2BO) baseBO);
        } else if (baseBO instanceof O2BO) {
            onMessageEvent((O2BO) baseBO);
        } else if (baseBO instanceof TemperatureBO) {
            onMessageEvent((TemperatureBO) baseBO);
        } else if (baseBO instanceof DoorBO) {
            onMessageEvent((DoorBO) baseBO);
        } else if (baseBO instanceof UltravioletLightBO) {
            onMessageEvent((UltravioletLightBO) baseBO);
        } else if (baseBO instanceof ElectronicScaleBO) {
            onMessageEvent((ElectronicScaleBO) baseBO);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(PeristalticPumpBO event) {
        //        if(isTesting){
        //            baseView.showToast(event.toString());
        //            isTesting=false;
        //            return;
        //        }
        byte modularNO = event.getModularNO();
        if (modularNO == PeristalticPumpBO.PeristalticPump_fluidIntake) {
            onFluidIntakePump(event);
        } else if (modularNO == PeristalticPumpBO.PeristalticPump_waste) {
            onWastePump(event);
        } else if (modularNO == PeristalticPumpBO.PeristalticPump_circulating) {
            onCirclePump(event);
        } else if (modularNO == PeristalticPumpBO.PeristalticPump_reclaim) {
            onReclaimPump(event);
        }
    }

    private void stopWeightWhenAllPumpStoped() {
        if (FluidIntakePumpController.getInstance().getSpeed() == 0 && WastePumpController.getInstance()
                                                                                          .getSpeed() == 0 && ReclaimPumpController
                .getInstance().getSpeed() == 0) {
            stopScheduleWeight();
        }
    }

    //计算进液需要的时间的理论值
    private int calculateFluidIntakeMax() {
        //        int max = 0;
        //        if (inputLiquidTask != null) {
        //            int time = (int) Math.round(UtilHelpers.calculateTimeBySpeedFlow(inputLiquidTask.getSpeed(), inputLiquidTask.getTotalAmount()));
        //            max = time;
        //        }
        //        return max;
        if (inputLiquidTask == null) {
            return 0;
        } else {
            //            if (inputLiquidTask.getShakeTableTask() != null) {
            //                return inputLiquidTask.getShakeTableTask().getTime() + inputLiquidTask.getTotalAmount();
            //            } else {
            //                return inputLiquidTask.getTotalAmount();
            //            }
            return inputLiquidTask.getTotalAmount();
        }
    }

    //计算排液需要的时间的理论值
    private int calculateDischargeMax() {
        //        int max = 0;
        //        if (wasteTask != null) {
        //            int time = (int) Math.round(UtilHelpers.calculateTimeBySpeedFlow(wasteTask.getSpeed(), wasteTask.getTotalAmount()));
        //            max = time;
        //        }
        //        return max;
        if (wasteTask == null) {
            return 0;
        } else {
            return wasteTask.getTotalAmount();
        }
    }

    //计算罐装需要的时间的理论值
    private int calculateCollectMax() {
        if (reclaimTask == null) {
            return 0;
        } else {
            return reclaimTask.getTotalAmount();
        }
    }

    //计算换液需要的时间的理论值
    private int calculateChangeLiquidMax() {
        //        int max = 0;
        //        if (changeLiquidTask != null) {
        //            ChangeLiquidBO changeLiquidBO = changeLiquidTask.getChangeLiquidBO();
        //            if (changeLiquidBO != null) {
        //                List<ChangeLiquidBO.ChangeLiquidTurn> changeLiquidTurnList = changeLiquidBO.getChangeLiquidTurnList();
        //                if (changeLiquidTurnList != null) {
        //                    for (ChangeLiquidBO.ChangeLiquidTurn changeLiquidTurn : changeLiquidTurnList) {
        //                        List<ChangeLiquidAmount> changeLiquidAmountList = changeLiquidTurn.getAmountList();
        //                        if (changeLiquidAmountList != null) {
        //                            for (ChangeLiquidAmount changeLiquidAmount : changeLiquidAmountList) {
        //                                int fluidTime = (int) Math.round(UtilHelpers.calculateTimeBySpeedFlow(ParamsPreferences.getInstance().getFluidIntakePumpSpeed(), changeLiquidAmount.getFluid()));
        //                                int dischargeTime = (int) Math.round(UtilHelpers.calculateTimeBySpeedFlow(ParamsPreferences.getInstance().getWastePumpSpeed(), changeLiquidAmount.getWaste()));
        //                                max += fluidTime;
        //                                max += dischargeTime;
        //                            }
        //                        }
        //                        max += changeLiquidTurn.getIntervalTime();
        //                    }
        //                }
        //            }
        //        }
        //        return max;

        int max = 0;
        if (changeLiquidTask != null) {
            ChangeLiquidBO changeLiquidBO = changeLiquidTask.getChangeLiquidBO();
            if (changeLiquidBO != null) {
                List<ChangeLiquidBO.ChangeLiquidTurn> changeLiquidTurnList = changeLiquidBO.getChangeLiquidTurnList();
                if (changeLiquidTurnList != null) {
                    for (ChangeLiquidBO.ChangeLiquidTurn changeLiquidTurn : changeLiquidTurnList) {
                        List<ChangeLiquidAmount> changeLiquidAmountList = changeLiquidTurn.getAmountList();
                        if (changeLiquidAmountList != null) {
                            for (ChangeLiquidAmount changeLiquidAmount : changeLiquidAmountList) {
                                int fluidTime = changeLiquidAmount.getFluid();
                                int dischargeTime = changeLiquidAmount.getWaste();
                                max += fluidTime;
                                max += dischargeTime;
                            }
                        }
                        max += changeLiquidTurn.getIntervalTime();
                    }
                }
            }
        }
        return max;
    }

    //计算至某轮某次的进度
    private int calculateChangeLiquidProgress(int turn, int index) {
        int progress = 0;
        if (changeLiquidTask != null) {
            ChangeLiquidBO changeLiquidBO = changeLiquidTask.getChangeLiquidBO();
            if (changeLiquidBO != null) {
                List<ChangeLiquidBO.ChangeLiquidTurn> changeLiquidTurnList = changeLiquidBO.getChangeLiquidTurnList();
                if (changeLiquidTurnList != null) {
                    for (int i = 0; i < changeLiquidTurnList.size() && i < turn; i++) {
                        ChangeLiquidBO.ChangeLiquidTurn changeLiquidTurn = changeLiquidTurnList.get(i);
                        List<ChangeLiquidAmount> changeLiquidAmountList = changeLiquidTurn.getAmountList();
                        if (changeLiquidAmountList != null) {
                            for (int j = 0; j < changeLiquidAmountList.size() && j < index; j++) {
                                ChangeLiquidAmount changeLiquidAmount = changeLiquidAmountList.get(j);
                                int fluidTime = changeLiquidAmount.getFluid();
                                int dischargeTime = changeLiquidAmount.getWaste();
                                progress += fluidTime;
                                progress += dischargeTime;
                            }
                        }
                        progress += changeLiquidTurn.getIntervalTime();
                    }
                }
            }
        }
        return progress;
    }

    //计算清洗管路需要的时间的理论值
    private int calculateCleanPipeMax() {
        int max = 0;
        if (cleanPipesTask != null) {
            //清洗一次的量
            int oneTime = cleanPipesTask.getFluidAmount() + cleanPipesTask.getWasteAmount() + cleanPipesTask.getLoopTime();
            max = oneTime * cleanPipesTask.getCleanNumbers();
        }
        return max;
    }

    private void resumeProgressBar() {
        if (isCleanPipes()) {
            baseView.resumeCleanPipeProgressBar();
        } else if (isChangingLiquid()) {
            baseView.resumeChangeLiquidProgressBar();
        } else if (isFluidIntaking) {
            baseView.resumeFluidInputProgressBar();
        }
    }

    private void pauseProgressBar() {
        if (isCleanPipes()) {
            baseView.pauseCleanPipeProgressBar();
        } else if (isChangingLiquid()) {
            baseView.pauseChangeLiquidProgressBar();
        } else if (isFluidIntaking) {
            baseView.pauseFluidInputProgressBar();
        }
    }

    private void onFluidIntakePump(PeristalticPumpBO peristalticPumpBO) {
        byte commondWord = peristalticPumpBO.getCommondWord();
        byte order = peristalticPumpBO.getOrder();
        if (commondWord == CommandWord.writeSucc[0]) {
            if (inputLiquidTask != null) {
                inputLiquidTask.ingToEd();
                //                handleLiquidInputTaskProgress(inputLiquidTask);
            }
            //            if(isChangingLiquid()){
            //                changeLiquidTask.ingToEd();
            //            }
            if (isCleanPipes()) {
                cleanPipesTask.ingToEd();
            }
            if (order == PeristalticPumpBO.star) {
                if (inputLiquidTask != null && inputLiquidTask.isSlowingDown()) {
                    inputLiquidTask.setSlowingDown(false);
                    inputLiquidTask.setSlowedDown(true);
                    return;
                }

                scheduleWeight();
                if (isChangingLiquid()) {
                    changeLiquidTask.ingToEd();
                }
                baseView.onOpenFluidIntakePumpSucc(peristalticPumpBO.getSpeed());
                activeDetectPumpFluidIntak();
                if (inputLiquidTask == null) {
                    return;
                    //                    inputLiquidTask = new LiquidLoopTask(LiquidLoopTask.TASK_Speed, PeristalticPumpBO.PeristalticPump_fluidIntake);
                    //                    inputLiquidTask.setSpeed(peristalticPumpBO.getSpeed());
                    //                    inputLiquidTask.setDirection(peristalticPumpBO.getDirection());
                    //                    inputLiquidTask.setState(LiquidLoopTask.STATE_STARTED);
                }
                //                inputLiquidTask.toRun();
                //                handleLiquidInputTaskProgress(inputLiquidTask);

                if (isResumingCulture) {
                    if (isALLResumed()) {
                        baseView.onResumeCultureSucc();
                        isResumingCulture = false;
                    }
                } else {
                    if (isCleanPipes()) {
                        if (cleanPipesTask.getCurrentCleanNumber() == 0) {
                            baseView.setCleanPipeProgressBar(calculateCleanPipeMax());
                            baseView.setPorgress4Visibility(View.VISIBLE);
                            //                            baseView.startCleanPipeProgressBar();
                        }
                    } else if (isChangingLiquid()) {

                    } else if (isFluidIntaking) {
                        baseView.setFluidInputProgressBar(calculateFluidIntakeMax());
                        baseView.setPorgress1Visibility(View.VISIBLE);
                        //                        baseView.startFluidInputProgressBar();
                    }
                }
            } else if (order == PeristalticPumpBO.stop) {
                baseView.onCloseFluidIntakePumpSucc();
                closeFluidIntakenFailedCount = 0;
                if (inputLiquidTask != null && inputLiquidTask.isChangingDirection()) {
                    inputLiquidTask.setChangingDirection(false);
                    return;
                }
                deActiveDetectPumpFluidIntak();
                if (isInitCultureLiquid) {
                    isInitCultureLiquid = false;
                    baseView.onInitCultureLiquidFinish();
                }
                if (isPauseingCulture) {
                    if (isALLPaused()) {
                        baseView.onPauseCultureSucc();
                        isPauseingCulture = false;
                    }
                } else {
                    if (isFluidIntaking && inputLiquidTask != null && inputLiquidTask
                            .getState() == LiquidLoopTask.STATE_END) {
                        int liquidType = inputLiquidTask.getLiquidType();
                        boolean isTerminate = inputLiquidTask.isTerminate();
                        isFluidIntaking = false;
                        inputLiquidTask.cancelCloseTask();
                        inputLiquidTask = null;
                        //结束时再称一下
                        //                        weight();
                        stopWeightWhenAllPumpStoped();

                        if (isSour) {
                            isSour = false;
                            baseView.onSourFinish();
                        } else if (isChangingLiquid()) {
                            if (!changeLiquidTask.isTerminate()) {
                                synchronized (changeLiquidTask) {
                                    changeLiquidTask.notifyAll();
                                }
                            } else {
                                synchronized (changeLiquidTask) {
                                    changeLiquidTask.notifyAll();
                                }
                                changeLiquidTask = null;
                                baseView.onTerminateChangeLiquid();
                                baseView.setPorgress4Visibility(View.GONE);
                            }
                        } else if (isCleanPipes()) {
                            if (!cleanPipesTask.isTerminate()) {
                                loopLiquid(cleanPipesTask.getLoopTime(), cleanPipesTask.getCirclingSpeed());
                            } else {
                                baseView.onTerminateCleanPipe();
                                baseView.setPorgress4Visibility(View.GONE);
                                cleanPipesTask = null;
                                isCleanPipes = false;
                            }
                        } else {
                            if (isTerminate) {
                                baseView.onTerminateFluidIntaken();
                                baseView.setPorgress1Visibility(View.GONE);
                            } else {
                                if (liquidType == LiquidLoopTask.Liquid_cell) {
                                    baseView.finishFluidIntakenCell();
                                } else if (liquidType == LiquidLoopTask.Liquid_viruses) {
                                    baseView.finishFluidIntakenViruses();
                                } else if (liquidType == LiquidLoopTask.Liquid_cryoprotectant) {
                                    baseView.finishFluidIntakenCryoprotectant();
                                } else {
                                    baseView.finishFluidIntaken();
                                }
                            }
                            baseView.stopFluidInputProgressBar();
                        }
                    } else {
                        stopWeightWhenAllPumpStoped();
                    }
                    //                    if (isChangingLiquid()) {
                    //                        synchronized (changeLiquidTask) {
                    //                            changeLiquidTask.notifyAll();
                    //                        }
                    //                    }
                }

            }
        } else if (commondWord == CommandWord.writeFail[0]) {
            baseView.showToast(peristalticPumpBO.toString());
            if (order == PeristalticPumpBO.star) {
                //如果失败，就取消关闭任务
                if (inputLiquidTask != null) {
                    inputLiquidTask.cancelCloseTask();
                }
                if (isFluidIntaking) {
                    isFluidIntaking = false;
                }
                if (isInitCultureLiquid) {
                    isInitCultureLiquid = false;
                }
            } else if (order == PeristalticPumpBO.stop) {
                //如果停止失败，则再发一次
                if (closeFluidIntakenFailedCount < maxCount) {
                    closePump(PeristalticPumpBO.PeristalticPump_fluidIntake);
                    closeFluidIntakenFailedCount++;
                }
            }
        } else if (commondWord == CommandWord.readSucc[0]) {
            if (inputLiquidTask == null) {
                return;
            }
            if (peristalticPumpBO.getAlarm() == PeristalticPumpBO.alarm_normal) {//正常
                if (inputLiquidTask.isPausedByAlarm() && inputLiquidTask.getState() == LiquidLoopTask.STATE_PAUSE) {//恢复
                    inputLiquidTask.setPausedByAlarm(false);
                    //                    inputLiquidTask.setPeristalticPumpBO(peristalticPumpBO);
                    resumePumpAfterAlarmDismiss(PeristalticPumpBO.PeristalticPump_fluidIntake);
                    baseView.onFluidIntakePumpAlarmDismiss(peristalticPumpBO.getSpeed());
                    resumeProgressBar();
                    //                    handleLiquidInputTaskProgress(inputLiquidTask);
                } else {
                    baseView.onReadFluidIntake(peristalticPumpBO.getDirection(), peristalticPumpBO.getSpeed(), null);
                }
            } else {//异常
                if (inputLiquidTask.getState() != LiquidLoopTask.STATE_PAUSE) {
                    inputLiquidTask.pausedByAlarm();
                    //                    inputLiquidTask.setPeristalticPumpBO(peristalticPumpBO);
                    //                    handleLiquidInputTaskProgress(inputLiquidTask);
                    pauseProgressBar();
                }
                baseView.onFluidIntakePumpAlarm(peristalticPumpBO.getAlarmStr());
            }
        } else if (commondWord == CommandWord.readFail[0]) {
            baseView.showToast(peristalticPumpBO.toString());
        }
    }

    private void finishLiquidPlan(LiquidLoopPlan liquidLoopPlan) {
        liquidLoopPlan.setIsFinished(true);
        liquidLoopPlanDao.update(liquidLoopPlan);
    }

    private void onWastePump(PeristalticPumpBO peristalticPumpBO) {
        byte commondWord = peristalticPumpBO.getCommondWord();
        byte order = peristalticPumpBO.getOrder();
        if (commondWord == CommandWord.writeSucc[0]) {
            if (wasteTask != null) {
                wasteTask.ingToEd();
                //                wasteTask.setPeristalticPumpBO(peristalticPumpBO);
                //                handleDischargeTaskProgress(wasteTask);
            }
            if (isChangingLiquid()) {
                changeLiquidTask.ingToEd();
            }
            if (order == PeristalticPumpBO.star) {
                if (wasteTask != null && wasteTask.isSlowingDown()) {
                    wasteTask.setSlowingDown(false);
                    wasteTask.setSlowedDown(true);
                    return;
                }

                baseView.onOpenWastePumpSucc(peristalticPumpBO.getSpeed());
                scheduleWeight();
                activeDetectPumpWaste();
                if (wasteTask == null) {
                    return;
                    //                    wasteTask = new LiquidLoopTask(LiquidLoopTask.TASK_Speed, PeristalticPumpBO.PeristalticPump_waste);
                    //                    wasteTask.setSpeed(peristalticPumpBO.getSpeed());
                    //                    wasteTask.setDirection(peristalticPumpBO.getDirection());
                    ////                    wasteTask.setPeristalticPumpBO(peristalticPumpBO);
                    //                    wasteTask.setState(LiquidLoopTask.STATE_STARTED);
                }
                if (isResumingCulture) {
                    if (isALLResumed()) {
                        baseView.onResumeCultureSucc();
                        isResumingCulture = false;
                    }
                } else {
                    if (isChangingLiquid()) {
                        if (changeLiquidTask.getCurrentChangeTurn() == 1 && changeLiquidTask.getCurrentChangeIndex() == 1) {
                            baseView.setChangeLiquidProgressBar(calculateChangeLiquidMax());
                            //                            baseView.startChangeLiquidProgressBar();
                            baseView.setPorgress4Visibility(View.VISIBLE);
                        }
                    } else if ((!isCleanPipes()) && isFluidOutTaking) {
                        baseView.setDischargeProgressBar(calculateDischargeMax());
                        baseView.setPorgress2Visibility(View.VISIBLE);
                    }
                }
            } else if (order == PeristalticPumpBO.stop) {
                baseView.onCloseWastePumpSucc();
                closeWastFailedCount = 0;
                if (wasteTask != null && wasteTask.isChangingDirection()) {
                    wasteTask.setChangingDirection(false);
                    return;
                }
                deActiveDetectPumpWaste();

                if (isPauseingCulture) {
                    if (isALLPaused()) {
                        baseView.onPauseCultureSucc();
                        isPauseingCulture = false;
                    }
                } else {
                    if (isFluidOutTaking && wasteTask != null && wasteTask.getState() == LiquidLoopTask.STATE_END) {
                        boolean isTerminate = wasteTask.isTerminate();
                        wasteTask.cancelCloseTask();
                        isFluidOutTaking = false;
                        wasteTask = null;
                        //                        weight();
                        stopWeightWhenAllPumpStoped();
                        if (isChangingLiquid()) {
                            if (!changeLiquidTask.isTerminate()) {
                                if (changeLiquidTask.getState() == OperateTask.STATE_END) {
                                    //在排液时终止换液任务
                                } else {
                                    fluidIntake(changeLiquidTask.getFluidCurrentAmount(), changeLiquidTask
                                            .getFluidSpeed(), changeLiquidTask.getLiquidType(), "系统", new Date(), null);
                                }
                            } else {
                                synchronized (changeLiquidTask) {
                                    changeLiquidTask.notifyAll();
                                }
                                changeLiquidTask = null;
                                baseView.onTerminateChangeLiquid();
                                baseView.setPorgress4Visibility(View.GONE);
                            }
                        } else if (isCleanPipes()) {
                            if (!cleanPipesTask.isTerminate()) {
                                cleanPipesTask.finishOneClean();
                                if (!cleanPipesTask.isFinishAllClean()) {
                                    baseView.cleanPipefinishOne(cleanPipesTask.getTaskName());
                                    //开始下一轮清洗
                                    fluidIntake(cleanPipesTask.getFluidAmount(), cleanPipesTask
                                            .getFluidSpeed(), LiquidLoopTask.Liquid_saline, "系统", new Date(), null);
                                } else {
                                    baseView.cleanPipefinishAll(cleanPipesTask.getTaskName());
                                    baseView.stopCleanPipeProgressBar();
                                    cleanPipesTask = null;
                                    isCleanPipes = false;
                                }
                            } else {
                                cleanPipesTask = null;
                                isCleanPipes = false;
                                baseView.onTerminateCleanPipe();
                                baseView.setPorgress4Visibility(View.GONE);
                            }

                        } else {
                            if (isTerminate) {
                                baseView.onTerminateDischarge();
                                baseView.setPorgress2Visibility(View.GONE);
                            } else {
                                baseView.finishDischarge();
                                baseView.stoptDischargeProgressBar();
                            }
                        }
                    } else {
                        stopWeightWhenAllPumpStoped();
                    }
                    //                    if (isChangingLiquid()) {
                    //                        if (changeLiquidTask.getState() == OperateTask.STATE_END) {
                    //                            //在排液时终止换液任务
                    //                        } else {
                    //                            fluidIntake(changeLiquidTask.getCurrentAmount(), changeLiquidTask.getFluidSpeed(), changeLiquidTask.getLiquidType(), null);
                    //                        }
                    //                    }
                }
            }
        } else if (commondWord == CommandWord.writeFail[0]) {
            baseView.showToast(peristalticPumpBO.toString());
            if (order == PeristalticPumpBO.star) {
                //如果失败，就取消关闭任务
                if (wasteTask != null) {
                    wasteTask.cancelCloseTask();
                }
                if (isFluidOutTaking) {
                    isFluidOutTaking = false;
                }
                //换液开启失败
                if (isChangingLiquid()) {
                    changeLiquidTask = null;
                }
            } else if (order == PeristalticPumpBO.stop) {
                //如果停止失败，则再发一次
                if (closeWastFailedCount < maxCount) {
                    closePump(PeristalticPumpBO.PeristalticPump_waste);
                    closeWastFailedCount++;
                }
            }
        } else if (commondWord == CommandWord.readSucc[0]) {
            if (wasteTask == null) {
                return;
            }
            if (peristalticPumpBO.getAlarm() == PeristalticPumpBO.alarm_normal) {//正常
                if (wasteTask.isPausedByAlarm() && wasteTask.getState() == LiquidLoopTask.STATE_PAUSE && peristalticPumpBO
                        .getSpeed() > 0) {//恢复
                    wasteTask.setPausedByAlarm(false);
                    //                    wasteTask.setPeristalticPumpBO(peristalticPumpBO);
                    resumePumpAfterAlarmDismiss(PeristalticPumpBO.PeristalticPump_waste);
                    baseView.onWastePumpAlarmDismiss(peristalticPumpBO.getSpeed());
                    //                    handleDischargeTaskProgress(wasteTask);
                    resumeProgressBar();
                } else {
                    baseView.onReadWaste(peristalticPumpBO.getDirection(), peristalticPumpBO.getSpeed(), null);
                }
            } else {//异常
                if (wasteTask.getState() != LiquidLoopTask.STATE_PAUSE) {
                    wasteTask.pausedByAlarm();
                    //                    wasteTask.setPeristalticPumpBO(peristalticPumpBO);
                    //                    handleDischargeTaskProgress(wasteTask);
                    pauseProgressBar();
                }
                baseView.onWastePumpAlarm(peristalticPumpBO.getAlarmStr());
            }
        } else if (commondWord == CommandWord.readFail[0]) {
            baseView.showToast(peristalticPumpBO.toString());
        }
    }

    private void onCirclePump(PeristalticPumpBO peristalticPumpBO) {
        byte commondWord = peristalticPumpBO.getCommondWord();
        byte order = peristalticPumpBO.getOrder();
        if (commondWord == CommandWord.writeSucc[0]) {
            if (circleTask != null) {
                circleTask.ingToEd();
                //                circleTask.setPeristalticPumpBO(peristalticPumpBO);
                //                handleLiquidTaskProgress(circleTask);
            }
            if (order == PeristalticPumpBO.star) {
                baseView.onOpenCirclePumpSucc(peristalticPumpBO.getSpeed());
                activeDetectPumpCircling();
                if (circleTask == null) {
                    return;
                    //                    circleTask = new LiquidLoopTask(LiquidLoopTask.TASK_Speed, PeristalticPumpBO.PeristalticPump_circulating);
                    //                    circleTask.setSpeed(peristalticPumpBO.getSpeed());
                    //                    circleTask.setDirection(peristalticPumpBO.getDirection());
                    //                    circleTask.setState(LiquidLoopTask.STATE_STARTED);
                }
                if (isResumingCulture) {
                    if (isALLResumed()) {
                        baseView.onResumeCultureSucc();
                        isResumingCulture = false;
                    }
                }
                if (isStartingCulture) {
                    if (isStartCultureSucc()) {
                        baseView.onStartCultureSucc();
                        isStartingCulture = false;
                    }
                }
                if (isCleanPipes()) {
                    Disposable disposable = Observable.interval(0, 1, TimeUnit.SECONDS).take((long) circleTask.getTime())
                                                      .subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers
                                    .mainThread()).map(new Function<Long,Integer>() {
                                @Override
                                public Integer apply(Long aLong) throws Exception {
                                    //aLong从0开始，所以+1
                                    return aLong.intValue() + 1;
                                }
                            }).subscribe(new Consumer<Integer>() {
                                //计算之前的progress
                                int progress = cleanPipesTask.getFluidAmount() * (cleanPipesTask
                                        .getCurrentCleanNumber() + 1) + (cleanPipesTask.getWasteAmount() + cleanPipesTask
                                        .getLoopTime()) * cleanPipesTask.getCurrentCleanNumber();

                                @Override
                                public void accept(Integer integer) throws Exception {
                                    baseView.setPorgress4(progress + integer);
                                }
                            });
                    circleTask.setDisposable(disposable);
                }
            } else if (order == PeristalticPumpBO.stop) {
                baseView.onCloseCirclePumpSucc();
                closeCirclingFailedCount = 0;
                if (circleTask != null && circleTask.isChangingDirection()) {
                    circleTask.setChangingDirection(false);
                    return;
                }
                deActiveDetectPumpCircling();
                if (isPauseingCulture) {
                    if (isALLPaused()) {
                        baseView.onPauseCultureSucc();
                        isPauseingCulture = false;
                    }
                }
                if (circleTask == null) {
                    return;
                }
                //循环完成后开始排液,由于进排液时都要停止循环泵，这里的循环是在进液完成后开始的
                if (isCleanPipes() && !isFluidIntaking && !isFluidOutTaking) {
                    if (circleTask.getDisposable() != null) {
                        circleTask.getDisposable().dispose();
                    }
                    if (!cleanPipesTask.isTerminate()) {
                        discharge(cleanPipesTask.getWasteAmount(), cleanPipesTask.getWasteSpeed(), "系统", new Date(), null);
                    } else {
                        baseView.onTerminateCleanPipe();
                        baseView.setPorgress4Visibility(View.GONE);
                        cleanPipesTask = null;
                        isCleanPipes = false;
                    }
                }
                circleTask.cancelCloseTask();
                circleTask = null;
            }
        } else if (commondWord == CommandWord.writeFail[0]) {
            baseView.showToast(peristalticPumpBO.toString());
            if (order == PeristalticPumpBO.star) {
                if (circleTask != null) {
                    circleTask.cancelCloseTask();
                }
            } else if (order == PeristalticPumpBO.stop) {
                //如果停止失败，则再发一次
                if (closeCirclingFailedCount < maxCount) {
                    closePump(PeristalticPumpBO.PeristalticPump_circulating);
                    closeCirclingFailedCount++;
                }
            }
        } else if (commondWord == CommandWord.readSucc[0]) {
            if (circleTask == null) {
                return;
            }
            if (peristalticPumpBO.getAlarm() == PeristalticPumpBO.alarm_normal) {//正常
                if (circleTask.isPausedByAlarm() && circleTask.getState() == LiquidLoopTask.STATE_PAUSE && peristalticPumpBO
                        .getSpeed() > 0) {//恢复
                    circleTask.setPausedByAlarm(false);
                    //                    circleTask.setPeristalticPumpBO(peristalticPumpBO);
                    resumePumpAfterAlarmDismiss(PeristalticPumpBO.PeristalticPump_circulating);
                    baseView.onCirclingPumpAlarmDismiss(peristalticPumpBO.getSpeed());
                } else {
                    baseView.onReadCircling(peristalticPumpBO.getDirection(), peristalticPumpBO.getSpeed(), null);
                    if (CirculatingPumpController.getInstance().isDirectionChangeWithoutExpected()) {
                        circlingChangeDirectionWithoutExpected++;
                    } else {
                        circlingChangeDirectionWithoutExpected = 0;
                    }
                    if (circlingChangeDirectionWithoutExpected >= maxCount) {
                        Operation operation = new Operation();
                        operation.setName(Operation.Operate_Circling);
                        operation.setData("循环泵纠正");
                        operation.setDateTime(new Date());
                        openPumpTask(PeristalticPumpBO.PeristalticPump_circulating, CirculatingPumpController.getInstance()
                                                                                                             .getSettingSpeed(), CirculatingPumpController
                                .getInstance().getSettingDirection(), operation);
                        circlingChangeDirectionWithoutExpected = 0;
                    }
                }
            } else {//异常
                if (circleTask.getState() != LiquidLoopTask.STATE_PAUSE) {
                    circleTask.pausedByAlarm();
                    //                    circleTask.setPeristalticPumpBO(peristalticPumpBO);
                }
                baseView.onCirclingPumpAlarm(peristalticPumpBO.getAlarmStr());
            }
        } else if (commondWord == CommandWord.readFail[0]) {
            baseView.showToast(peristalticPumpBO.toString());
        }
    }

    private void onReclaimPump(PeristalticPumpBO peristalticPumpBO) {
        byte commondWord = peristalticPumpBO.getCommondWord();
        byte order = peristalticPumpBO.getOrder();
        if (commondWord == CommandWord.writeSucc[0]) {
            if (reclaimTask != null) {
                reclaimTask.ingToEd();
                //                reclaimTask.setPeristalticPumpBO(peristalticPumpBO);
                //                handleCollectTaskProgress(reclaimTask);
            }
            if (order == PeristalticPumpBO.star) {
                if (reclaimTask != null && reclaimTask.isSlowingDown()) {
                    reclaimTask.setSlowingDown(false);
                    reclaimTask.setSlowedDown(true);
                    return;
                }
                baseView.onOpenReclaimPumpSucc(peristalticPumpBO.getSpeed());
                scheduleWeight();
                activeDetectPumpReclaim();
                if (reclaimTask == null) {
                    reclaimTask = new LiquidLoopTask(LiquidLoopTask.TASK_Speed, PeristalticPumpBO.PeristalticPump_reclaim);
                    reclaimTask.setSpeed(peristalticPumpBO.getSpeed());
                    reclaimTask.setDirection(peristalticPumpBO.getDirection());
                    //                    reclaimTask.setPeristalticPumpBO(peristalticPumpBO);
                    reclaimTask.setState(LiquidLoopTask.STATE_STARTED);
                }
                if (isResumingCulture) {
                    if (isALLResumed()) {
                        baseView.onResumeCultureSucc();
                        isResumingCulture = false;
                    }
                } else {
                    baseView.setCollectProgressBar(calculateCollectMax());
                    baseView.setPorgress3Visibility(View.VISIBLE);
                }
            } else if (order == PeristalticPumpBO.stop) {
                baseView.onCloseReclaimPumpSucc();
                closeReclaimFailedCount = 0;
                if (reclaimTask != null && reclaimTask.isChangingDirection()) {
                    reclaimTask.setChangingDirection(false);
                    return;
                }
                deActiveDetectPumpReclaim();
                stopWeightWhenAllPumpStoped();
                //                if (reclaimTask != null) {
                //                    reclaimTask.cancelCloseTask();
                //                    reclaimTask=null;
                //                }
                if (isPauseingCulture) {
                    if (isALLPaused()) {
                        baseView.onPauseCultureSucc();
                        isPauseingCulture = false;
                    }
                } else if (isCollecting && reclaimTask != null && reclaimTask.getState() == LiquidLoopTask.STATE_END) {
                    boolean isTerminate = reclaimTask.isTerminate();
                    reclaimTask.cancelCloseTask();
                    isCollecting = false;
                    reclaimTask = null;
                    //                        weight();
                    if (isTerminate) {
                        baseView.onTerminateCollect();
                        baseView.setPorgress3Visibility(View.GONE);
                    } else {
                        baseView.finishCollect();
                        baseView.stopCollectProgressBar();
                    }
                    stopWeightWhenAllPumpStoped();
                }
            }
        } else if (commondWord == CommandWord.writeFail[0]) {
            baseView.showToast(peristalticPumpBO.toString());
            if (order == PeristalticPumpBO.star) {
                if (reclaimTask != null) {
                    reclaimTask.cancelCloseTask();
                }
                if (isCollecting) {
                    isCollecting = false;
                }
            } else if (order == PeristalticPumpBO.stop) {
                //如果停止失败，则再发一次
                if (closeReclaimFailedCount < maxCount) {
                    closePump(PeristalticPumpBO.PeristalticPump_reclaim);
                    closeReclaimFailedCount++;
                }
            }
        } else if (commondWord == CommandWord.readSucc[0]) {
            if (reclaimTask == null) {
                return;
            }
            if (peristalticPumpBO.getAlarm() == PeristalticPumpBO.alarm_normal) {//正常
                if (reclaimTask.isPausedByAlarm() && reclaimTask
                        .getState() == LiquidLoopTask.STATE_PAUSE && peristalticPumpBO.getSpeed() > 0) {//恢复
                    reclaimTask.setPausedByAlarm(false);
                    //                    reclaimTask.setPeristalticPumpBO(peristalticPumpBO);
                    resumePumpAfterAlarmDismiss(PeristalticPumpBO.PeristalticPump_reclaim);
                    baseView.onReclaimPumpAlarmDismiss(peristalticPumpBO.getSpeed());
                    //                    handleCollectTaskProgress(reclaimTask);
                    resumeProgressBar();
                } else {
                    baseView.onReadReclaim(peristalticPumpBO.getDirection(), peristalticPumpBO.getSpeed(), null);
                }
            } else {//异常
                if (reclaimTask.getState() != LiquidLoopTask.STATE_PAUSE) {
                    reclaimTask.pausedByAlarm();
                    //                    reclaimTask.setPeristalticPumpBO(peristalticPumpBO);
                    //                    handleCollectTaskProgress(reclaimTask);
                    pauseProgressBar();
                }
                baseView.onReclaimPumpAlarm(peristalticPumpBO.getAlarmStr());
            }
        } else if (commondWord == CommandWord.readFail[0]) {
            baseView.showToast(peristalticPumpBO.toString());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MagneticStirrerBO event) {
        byte commondWord = event.getCommondWord();
        if (commondWord == CommandWord.writeSucc[0]) {
            if (stirrerTask != null) {
                //                stirrerTask.setMagneticStirrerBO(event);
                //                if(event.getSpeed()==stirrerTask.getSpeed()) {
                //                    stirrerTask.ingToEd();
                //                }
                stirrerTask.ingToEd();
            }
            if (event.getOrder() == MagneticStirrerBO.star) {
                baseView.onOpenStirrerSucc(event.getSpeed());
                if (isStartingCulture && event.getSpeed() == stirrerTask.getSpeed()) {
                    if (isStartCultureSucc()) {
                        baseView.onStartCultureSucc();
                        isStartingCulture = false;
                    }
                }
            } else if (event.getOrder() == MagneticStirrerBO.stop) {
                baseView.onCloseStirrerSucc();
            }
        } else if (commondWord == CommandWord.writeFail[0]) {

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CultureTankBO event) {
        byte commondWord = event.getCommondWord();
        if (commondWord == CommandWord.writeSucc[0]) {
            if (cultureTankTask != null) {
                //                cultureTankTask.setCultureTankBO(event);
                cultureTankTask.ingToEd();
            }
            if (event.getOrder() == CultureTankBO.star) {
                baseView.onOpenCultureTankSucc(event.getSpeed());
                if (isStartingCulture) {
                    if (isStartCultureSucc()) {
                        baseView.onStartCultureSucc();
                        isStartingCulture = false;
                    }
                }
            } else if (event.getOrder() == CultureTankBO.stop) {
                baseView.onCloseCultureTankSucc();
            }
        } else if (commondWord == CommandWord.writeFail[0]) {

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(IncubatorBO event) {
        if (event.getCommondWord() == CommandWord.writeSucc[0]) {
            if (incubatorTask != null) {
                incubatorTask.setIncubatorBO(event);
                incubatorTask.ingToEd();
            }
            if (event.getOrder() == IncubatorBO.star) {
                baseView.onOpenIncubatorSucc();
            } else if (event.getOrder() == IncubatorBO.stop) {
                baseView.onCloseIncubatorSucc();
            }
        }
    }

    //发现环境数据异常，立马发送给服务器
    private synchronized void reportErrorEnvironment() {
        Observable<EnvironmentLog> observable = deviceRuntimeLogModle.sendEnvironmentLog(CO2Controller.getInstance()
                                                                                                      .getCurrentValue(), O2Controller
                .getInstance().getCurrentValue(), TemperatureController.getInstance()
                                                                       .getCurrentValue(), EnvironmentLog.ABNORMAL);
        deviceRuntimeLogModle.toSubscribe(observable, new RockBaseObserver<EnvironmentLog>(this, null) {
            @Override
            protected void onBaseNext(EnvironmentLog data) {

            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CO2BO event) {
        if (event.getCommondWord() == CommandWord.readSucc[0]) {
            if (event.getCO2() > ParamConsts.CO2_exception) {
                asyncSession.insert(new ExceptionInfo(null, new Date(), ProjectManager.getInstance()
                                                                                      .getProjectId(), ExperimentStageManager
                        .getInstance().getStageId(), ExceptionCode.CO2, String
                        .valueOf(event.getCO2()), ExceptionType.ERROR_LOGIC));
            } else {
                currentCO2 = event.getCO2();
                baseView.onReceiveCO2(currentCO2);
                //                asyncSession.insert(new CO2(null, ProjectManager.getInstance().getProjectId(), ExperimentStageManager.getInstance().getStageId(), new Date(), currentCO2));
            }
        } else if (event.getCommondWord() == CommandWord.writeSucc[0]) {
            if (event.getOrder() == CO2BO.write) {
                baseView.onReceiveCO2(currentCO2);
                baseView.onSetCO2(event.getCO2());
            } else if (event.getOrder() == CO2BO.stop) {
                baseView.showToast(event.toString());
            }
        } else if (event.getCommondWord() == CommandWord.readFail[0]) {
            baseView.readCO2Failed();
        } else if (event.getCommondWord() == CommandWord.writeFail[0]) {
            if (event.getOrder() == CO2BO.write) {
                baseView.setCO2Failed();
            } else if (event.getOrder() == CO2BO.stop) {
                baseView.showToast(event.toString());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(O2BO event) {
        if (event.getCommondWord() == CommandWord.readSucc[0]) {
            if (event.getO2() > ParamConsts.O2_exception) {
                asyncSession.insert(new ExceptionInfo(null, new Date(), ProjectManager.getInstance()
                                                                                      .getProjectId(), ExperimentStageManager
                        .getInstance().getStageId(), ExceptionCode.O2, String
                        .valueOf(event.getO2()), ExceptionType.ERROR_LOGIC));
            } else {
                currentO2 = event.getO2();
                baseView.onReceiveO2(currentO2);
                //                asyncSession.insert(new O2(null, ProjectManager.getInstance().getProjectId(), ExperimentStageManager.getInstance().getStageId(), new Date(), currentO2));
            }
        } else if (event.getCommondWord() == CommandWord.writeSucc[0]) {
            if (event.getOrder() == O2BO.write) {
                baseView.onReceiveO2(currentO2);
                baseView.onSetO2(event.getO2());
            } else if (event.getOrder() == O2BO.stop) {
                baseView.showToast(event.toString());
            }
        } else if (event.getCommondWord() == CommandWord.readFail[0]) {
            baseView.readO2Failed();
        } else if (event.getCommondWord() == CommandWord.writeFail[0]) {
            if (event.getOrder() == O2BO.write) {
                baseView.setO2Failed();
            } else if (event.getOrder() == O2BO.stop) {
                baseView.showToast(event.toString());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TemperatureBO event) {
        if (event.getCommondWord() == CommandWord.readSucc[0]) {
            if (event.getTemperature() > ParamConsts.temperature_exception) {
                asyncSession.insert(new ExceptionInfo(null, new Date(), ProjectManager.getInstance()
                                                                                      .getProjectId(), ExperimentStageManager
                        .getInstance().getStageId(), ExceptionCode.TEMPERATURE, String
                        .valueOf(event.getTemperature()), ExceptionType.ERROR_LOGIC));
            } else {
                //                currentTemperature = event.getTemperature();
                currentTemperature = event.getAdjustTemperature();
                baseView.onReceiveTemperature(currentTemperature);
                if (isProjectStarted) {
                    //异常数据立马发送给服务器
                    if (!TemperatureController.getInstance().isInControl() || !CO2Controller.getInstance()
                                                                                            .isInControl() || !O2Controller
                            .getInstance().isInControl()) {
                        reportErrorEnvironment();
                    }
                }
                //                asyncSession.insert(new Temperature(null, ProjectManager.getInstance().getProjectId(), ExperimentStageManager.getInstance().getStageId(), new Date(), currentTemperature));
            }
        } else if (event.getCommondWord() == CommandWord.writeSucc[0]) {
            if (event.getOrder() == TemperatureBO.write) {
                //                ParamsPreferences.getInstance().setTemperatureCommit(event.getTemperature());
                baseView.onReceiveTemperature(currentTemperature);
                baseView.onSetTemperature(event.getTemperature());
            } else if (event.getOrder() == TemperatureBO.stop) {
                baseView.showToast(event.toString());
            }
        } else if (event.getCommondWord() == CommandWord.readFail[0]) {
            baseView.readTemperatureFailed();
        } else if (event.getCommondWord() == CommandWord.writeFail[0]) {
            if (event.getOrder() == TemperatureBO.write) {
                baseView.setTemperatureFailed();
            } else if (event.getOrder() == TemperatureBO.stop) {
                baseView.showToast(event.toString());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LiquidLevelBO event) {
        if (event.getCommondWord() == CommandWord.readSucc[0]) {
            if (event.getStatus() == LiquidLevelBO.LiquidLevel_Ok) {
                levelLiquid_warning = 0;
            } else {
                levelLiquid_warning++;
            }
            if (levelLiquid_warning >= 3) {
                baseView.liquidLevelWarning();
            } else {
                baseView.liquidLevelOk();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UltravioletLightBO event) {
        if (event.getCommondWord() == CommandWord.writeSucc[0]) {
            if (event.getOrder() == UltravioletLightBO.on) {
                baseView.onOpenUltravioletLightSucc();
            } else if (event.getOrder() == UltravioletLightBO.off) {
                baseView.onCloseUltravioletLightSucc();
                if (isStartNewProject) {
                    baseView.onStartNewProject();
                }
            }
            if (ultravioletLightTask != null) {
                ultravioletLightTask.ingToEd();
            }
        }
    }

    private void adjustProgressMax(int increase) {
        if (isCleanPipes()) {
            baseView.adjustCleanPipeProgressBar(increase);
        } else if (isChangingLiquid()) {
            baseView.adjustChangeLiquidProgressBar(increase);
        } else if (isFluidIntaking) {
            baseView.adjustFluidInputProgressBar(increase);
        } else if (isFluidOutTaking) {
            baseView.adjustDischargeProgressBar(increase);
        } else if (isCollecting) {
            baseView.adjustCollectProgressBar(increase);
        }
    }

    //判断是否没有液体了
    private void isNoLiquid() {

    }

    //误差小于1
    private int error = 1;
    //减速阈值
    private int slowDownPoint = 10;
    //减速的速度
    private int slowDownSpeed = 20;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ElectronicScaleBO event) {
        if (event.getCommondWord() == CommandWord.writeSucc[0]) {
            ParamsPreferences.getInstance().setADCommit(event.getAd());
            baseView.peelSucc(event.getAd());
        } else if (event.getCommondWord() == CommandWord.readSucc[0]) {
            readWeightFailedTimes = 0;
            double weight = event.getAdjustWeight();
            //读到超大值，设为0
            if (weight > ParamConsts.weight_exception) {
                asyncSession.insert(new ExceptionInfo(null, new Date(), ProjectManager.getInstance()
                                                                                      .getProjectId(), ExperimentStageManager
                        .getInstance().getStageId(), ExceptionCode.WEIGHT, String
                        .valueOf(weight), ExceptionType.ERROR_LOGIC));
                event.setWeight(0);
            }
            baseView.weightSucc(weight);
            if (isFluidIntaking && inputLiquidTask != null) {
                if (inputLiquidTask.getState() == LiquidLoopTask.STATE_UNSTART) {
                    inputLiquidTask.setInitWeight(weight);
                    synchronized (inputLiquidTask) {
                        inputLiquidTask.notifyAll();
                    }
                } else {
                    int diff = (int) (weight - inputLiquidTask.getInitWeight());
                    if (Math.abs(diff - inputLiquidTask.getTotalAmount()) <= error || diff >= inputLiquidTask
                            .getTotalAmount()) {
                        synchronized (inputLiquidTask) {
                            inputLiquidTask.notifyAll();
                        }
                    } else if (!inputLiquidTask.isSlowedDown() && (inputLiquidTask
                            .getTotalAmount() - diff) <= slowDownPoint) {
                        inputLiquidTask.setSlowingDown(true);
                        if (inputLiquidTask.getSpeed() > slowDownSpeed) {
                            openPump(PeristalticPumpBO.PeristalticPump_fluidIntake, slowDownSpeed, inputLiquidTask
                                    .getDirection());
                        }
                    }
                    if (isCleanPipes()) {
                        int progress = (cleanPipesTask.getFluidAmount() + cleanPipesTask.getLoopTime() + cleanPipesTask
                                .getWasteAmount()) * cleanPipesTask.getCurrentCleanNumber();
                        baseView.setPorgress4(progress + diff);
                    } else if (isChangingLiquid()) {
                        int turn = changeLiquidTask.getCurrentChangeTurn();
                        int index = changeLiquidTask.getCurrentChangeIndex();
                        int progress = calculateChangeLiquidProgress(turn, index - 1) + changeLiquidTask
                                .getWasteCurrentAmount();
                        baseView.setPorgress4(progress + diff);
                        if (Math.abs(progress + diff - baseView.getProgress4Max()) <= error) {
                            baseView.setPorgress4Visibility(View.GONE);
                        }
                    } else {
                        baseView.setPorgress1(diff);
                        if (Math.abs(diff - baseView.getProgress1Max()) <= error) {
                            baseView.setPorgress1Visibility(View.GONE);
                        }
                    }

                }
            } else if (isFluidOutTaking && wasteTask != null) {
                if (wasteTask.getState() == LiquidLoopTask.STATE_UNSTART) {
                    wasteTask.setInitWeight(weight);
                    synchronized (wasteTask) {
                        wasteTask.notifyAll();
                    }
                } else {
                    //排液是减少重量的
                    int diff = (int) (wasteTask.getInitWeight() - weight);
                    if (Math.abs(diff - wasteTask.getTotalAmount()) <= error || diff >= wasteTask.getTotalAmount()) {
                        synchronized (wasteTask) {
                            wasteTask.notifyAll();
                        }
                    } else if (!wasteTask.isSlowedDown() && (wasteTask.getTotalAmount() - diff) <= slowDownPoint) {
                        wasteTask.setSlowingDown(true);
                        if (wasteTask.getSpeed() > slowDownSpeed) {
                            openPump(PeristalticPumpBO.PeristalticPump_waste, slowDownSpeed, wasteTask.getDirection());
                        }
                    }
                    if (isCleanPipes()) {
                        int progress = (cleanPipesTask.getFluidAmount() + cleanPipesTask.getLoopTime()) * (cleanPipesTask
                                .getCurrentCleanNumber() + 1) + cleanPipesTask.getWasteAmount() * cleanPipesTask
                                .getCurrentCleanNumber();
                        baseView.setPorgress4(progress + diff);
                        if (Math.abs(progress + diff - baseView.getProgress4Max()) <= error) {
                            baseView.setPorgress4Visibility(View.GONE);
                        }
                    } else if (isChangingLiquid()) {
                        int turn = changeLiquidTask.getCurrentChangeTurn();
                        int index = changeLiquidTask.getCurrentChangeIndex();
                        int progress = calculateChangeLiquidProgress(turn, index - 1);
                        baseView.setPorgress4(progress + diff);
                    } else {
                        baseView.setPorgress2(diff);
                        if (Math.abs(diff - baseView.getProgress2Max()) <= error) {
                            baseView.setPorgress2Visibility(View.GONE);
                        }
                    }

                }
            } else if (isCollecting && reclaimTask != null) {
                if (reclaimTask.getState() == LiquidLoopTask.STATE_UNSTART) {
                    reclaimTask.setInitWeight(weight);
                    synchronized (reclaimTask) {
                        reclaimTask.notifyAll();
                    }
                } else {
                    //罐装是减少重量的
                    int diff = (int) (reclaimTask.getInitWeight() - weight);
                    if (Math.abs(diff - reclaimTask.getTotalAmount()) <= error || diff >= reclaimTask.getTotalAmount()) {
                        baseView.setPorgress3Visibility(View.GONE);
                        synchronized (reclaimTask) {
                            reclaimTask.notifyAll();
                        }
                    } else if (!reclaimTask.isSlowedDown() && (reclaimTask.getTotalAmount() - diff) <= slowDownPoint) {
                        reclaimTask.setSlowingDown(true);
                        if (reclaimTask.getSpeed() > slowDownSpeed) {
                            openPump(PeristalticPumpBO.PeristalticPump_reclaim, slowDownSpeed, reclaimTask.getDirection());
                        }
                    }
                    baseView.setPorgress3(diff);
                }
            }
        } else if (event.getCommondWord() == CommandWord.writeFail[0]) {
            baseView.peelFail();
        } else if (event.getCommondWord() == CommandWord.readFail[0]) {
            baseView.weightFail();
            readWeightFailedTimes++;
            //超过3次称重读失败，停止正在进行的操作
            if (readWeightFailedTimes < 3) {
                return;
            }

            boolean isShowCancelMsg = false;
            if (changeLiquidTask != null) {
                clearChangeLiquidTask();
                closePump(PeristalticPumpBO.PeristalticPump_fluidIntake);
                closePump(PeristalticPumpBO.PeristalticPump_waste);
                changeLiquidTask = null;
                isShowCancelMsg = true;
            }
            if (cleanPipesTask != null) {
                clearCleanPipeTask();
                closePump(PeristalticPumpBO.PeristalticPump_fluidIntake);
                closePump(PeristalticPumpBO.PeristalticPump_waste);
                closePump(PeristalticPumpBO.PeristalticPump_circulating);
                cleanPipesTask = null;
                isShowCancelMsg = true;
            }
            if (inputLiquidTask != null) {
                if (inputLiquidTask.isRunned()) {
                    closePumpTask(PeristalticPumpBO.PeristalticPump_fluidIntake, null);
                    inputLiquidTask = null;
                    isShowCancelMsg = true;
                }
            }
            if (wasteTask != null) {
                if (wasteTask.isRunned()) {
                    closePumpTask(PeristalticPumpBO.PeristalticPump_waste, null);
                    wasteTask = null;
                    isShowCancelMsg = true;
                }
            }
            if (reclaimTask != null) {
                if (reclaimTask.isRunned()) {
                    closePumpTask(PeristalticPumpBO.PeristalticPump_reclaim, null);
                    reclaimTask = null;
                    isShowCancelMsg = true;
                }
            }
            if (isShowCancelMsg) {
                baseView.showToast("称重失败，任务取消");
            }
            baseView.onWeightFailed();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DoorBO event) {
        if (event.getCommondWord() == CommandWord.writeSucc[0]) {
            if (event.getOrder() == DoorBO.open) {
                baseView.onDoorOpen();
            } else if (event.getOrder() == DoorBO.close) {
                baseView.onDoorColse();
            } else if (event.getOrder() == DoorBO.stop) {
                baseView.onDoorStop();
            }
        } else if (event.getCommondWord() == CommandWord.readSucc[0]) {
            baseView.onReadDoor(event.getStatusStr());
        }
    }

    //----------------------------------------------------------------------------------------------
    private int getPumpSpeed(LiquidLoopTask liquidLoopTask) {
        if (liquidLoopTask == null) {
            return 0;
        } else {
            return liquidLoopTask.getSpeed();
        }
    }

    @Override
    int getFluidIntakenPumpSpeed() {
        return getPumpSpeed(inputLiquidTask);
    }

    @Override
    public void detachView() {
        EventBus.getDefault().unregister(this);
        if (scheduledFutureExperiment != null) {
            scheduledFutureExperiment.cancel(true);
        }
        cancelScheduleChangeAir();
        super.detachView();
    }

    public void shutDown() {
        DeviceModle deviceModle = new DeviceModle();
        deviceModle.shutDown();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DeviceBO event) {
        if (event.getCommondWord() == CommandWord.writeSucc[0]) {
            if (event.getModularNO() == DeviceBO.deviceMAC_SHUTDOWN) {
                baseView.showToast(event.toString());
            }
        } else {
            baseView.showToast(event.toString());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ValveBO event) {
        if (event.getCommondWord() == CommandWord.writeSucc[0]) {
            byte modularNO = event.getModularNO();
            byte order = event.getOrder();
            if (modularNO == ValveBO.Valve_saline) {
                if (order == ValveBO.open) {
                    baseView.onSalineOpen();
                } else if (order == ValveBO.close) {
                    baseView.onSalineClose();
                }
            } else if (modularNO == ValveBO.Valve_medium) {
                if (order == ValveBO.open) {
                    baseView.onMediumOpen();
                } else if (order == ValveBO.close) {
                    baseView.onMediumClose();
                }
            } else if (modularNO == ValveBO.Valve_shaker) {
                if (order == ValveBO.open) {
                    baseView.onShakerOpen();
                    if (shakeTableTask != null) {
                        shakeTableTask.ingToEd();
                    }
                    //                    if (isFluidIntaking && inputLiquidTask != null) {
                    //                        if(!isCleanPipes()&&!isChangingLiquid()){
                    //                            baseView.setFluidInputProgressBar(calculateFluidIntakeMax());
                    //                        }
                    //                        if (shakeTableTask != null) {
                    //                            Disposable disposable = Observable.interval(0, 1, TimeUnit.SECONDS)
                    //                                    .take(shakeTableTask.getTime())
                    //                                    .subscribeOn(Schedulers.newThread())
                    //                                    .observeOn(AndroidSchedulers.mainThread())
                    //                                    .map(new Function<Long, Integer>() {
                    //                                        @Override
                    //                                        public Integer apply(Long aLong) throws Exception {
                    //                                            //aLong从0开始，所以+1
                    //                                            return aLong.intValue() + 1;
                    //                                        }
                    //                                    })
                    //                                    .subscribe(new Consumer<Integer>() {
                    //                                        @Override
                    //                                        public void accept(Integer integer) throws Exception {
                    //                                            baseView.setPorgress1(integer);
                    //                                        }
                    //                                    });
                    //                            shakeTableTask.setProgressBarDisposable(disposable);
                    //                        }
                    //                    }
                } else if (order == ValveBO.close) {
                    baseView.onShakerClose();
                    if (shakeTableTask != null) {
                        shakeTableTask.ingToEd();
                        shakeTableTask.cancelCloseTask();
                    }
                    if (isFluidIntaking && inputLiquidTask != null) {
                        //                        if (shakeTableTask.getProgressBarDisposable() != null) {
                        //                            shakeTableTask.getProgressBarDisposable().dispose();
                        //                        }
                        synchronized (inputLiquidTask) {
                            inputLiquidTask.notifyAll();
                        }
                    }
                }
            }
        } else {
            baseView.showToast(event.toString());
        }
    }

    public void test() {
        synchronized (changeLiquidTask) {
            //            changeLiquidTask.setCurrentChangeIndex(changeLiquidTask.getCurrentChangeIndex()+1);
            changeLiquidTask.notifyAll();
        }
    }
}
